asp.net mvc razor string with double quotes - asp.net-mvc

I am trying to use a string with double quotes but unable to get it work
#{
string disableMessage = "";
var disableAttr = "";
if (ViewBag.IsApplicable)
{
disableMessage = "You dont have permission to add new Item.";
disableAttr = "class=" + "disableItem" +" title="+"\""+ disableMessage +"\"";
}
}
expected: disableAttr as
class=disableItem title="You dont have permission to add new demand."
I got struck at getting double quotes for title attribute.

Why not deal with the two attributes separately:
#{
string disableTitle = null;
string disableClass = null;
if (ViewBag.IsApplicable)
{
disableTitle = "You dont have permission to add new Item.";
disableClass = "disableItem";
}
}
<div class="#disableClass" title="#disableTitle">Content</div>
Note that Razor V2 (in MVC4+) has a "conditional attribute" feature. When an attribute value is null, then Razor won't output anything at all for the attribute. So in the example above, if ViewBag.IsApplicable is false, the output will be:
<div>Content</div>

Ross's answer is much more elegant. However, keeping the line of your original code, you could do the following:
disableAttr = "class='disableItem'" +" title='"+ disableMessage +"'";
This will render the following text inside disableAttr:
class='disableItem' title='your_message_here';

Related

Does Google Dart have something like regex.exec()?

I read the documentation (https://api.dartlang.org/stable/1.21.1/dart-core/RegExp-class.html) but could not find I was looking for. Either I didnt understand it or I overlooked something.
I am trying to replicate the following in google dart:
var regex = /foo_(\d+)/g,
str = "text foo_123 more text foo_456 foo_789 end text",
match = null;
while (match = regex.exec(str)) {
console.log(match); // matched capture groups
console.log(match.index); // index of where match starts in string
console.log(regex.lastIndex); // index of where match ends in string
}
I also created a jsfiddle: https://jsfiddle.net/h3z88udz/
Does dart have something like regex exec()?
RegExp.allMatches looks like it does what you want.
var regex = new RegExp(r"foo_(\d+)");
var str = "text foo_123 more text foo_456 foo_789 end text";
void main() {
for (var match in regex.allMatches(str)) {
print(match);
print(match.start);
print(match.end);
}
}
https://dartpad.dartlang.org/dd1c136fa49ada4f2ad4ffc0659aab51

How do I get the ASP.Net MVC Password HTML Helper to show characters as I type?

I'm using the Password HTML Helper in MVC5 to hide the social security number as it is entered.
#Html.Password("s", null, new { #maxlength = 9, autocomplete = "off" })
The problem I see with it is you just see dots as you type. Is there any way the helper behavior can be modified to show the characters you are typing in for a second or two then have them transformed to dots? That behavior would let the user confirm they are typing in the correct character. If the helper behavior cannot be modified is there another way to accomplish this?
I found this fiddle maybe you can use this as an option
http://jsfiddle.net/Ngtp7/
$(function(){
$(".showpassword").each(function(index,input) {
var $input = $(input);
$('<label class="showpasswordlabel"/>').append(
$("<input type='checkbox' class='showpasswordcheckbox' />").click(function() {
var change = $(this).is(":checked") ? "text" : "password";
var rep = $("<input type='" + change + "' />")
.attr("id", $input.attr("id"))
.attr("name", $input.attr("name"))
.attr('class', $input.attr('class'))
.val($input.val())
.insertBefore($input);
$input.remove();
$input = rep;
})
).append($("<span/>").text("Show password")).insertAfter($input);
});
});

SQL CLR User Defined Function (C#) adds null character (\0) in between every existing character in String being returned

This one has kept me stumped for a couple of days now.
It's my first dabble with CLR & UDF ...
I have created a user defined function that takes a multiline String as input, scans it and replaces a certain line in the string with an alternative if found. If it is not found, it simply appends the desired line at the end. (See code)
The problem, it seems, comes when the final String (or Stringbuilder) is converted to an SqlString or SqlChars. The converted, returned String always contains the Nul character as every second character (viewing via console output, they are displayed as spaces).
I'm probably missing something fundamental on UDF and/or CLR.
Please Help!!
Code (I leave in the commented Stringbuilder which was my initial attempt... changed to normal String in a desperate attempt to find the issue):
[Microsoft.SqlServer.Server.SqlFunction]
[return: SqlFacet(MaxSize = -1, IsFixedLength = false)]
//public static SqlString udf_OmaChangeJob(String omaIn, SqlInt32 jobNumber) {
public static SqlChars udf_OmaChangeJob(String omaIn, SqlInt32 jobNumber) {
if (omaIn == null || omaIn.ToString().Length <= 0) return new SqlChars("");
String[] lines = Regex.Split(omaIn.ToString(), "\r\n");
Regex JobTag = new Regex(#"^JOB=.+$");
//StringBuilder buffer = new StringBuilder();
String buffer = String.Empty;
bool matched = false;
foreach (var line in lines) {
if (!JobTag.IsMatch(line))
//buffer.AppendLine(line);
buffer += line + "\r\n";
else {
//buffer.AppendLine("JOB=" + jobNumber);
buffer += ("JOB=" + jobNumber + "\r\n");
matched = true;
}
}
if (!matched) //buffer.AppendLine("JOB=" + jobNumber);
buffer += ("JOB=" + jobNumber) + "\r\n";
//return new SqlString(buffer.ToString().Replace("\0",String.Empty)) + "blablabla";
// buffer = buffer.Replace("\0", "|");
return new SqlChars(buffer + "\r\nTheEnd");
}
I know in my experiences, the omaIn parameter should be of type SqlString and when you go to collect its value/process it, set a local variable:
string omaString = omaIn != SqlString.Null ? omaIn.Value : string.empty;
Then when you return on any code path, to rewrap the string in C#, you'd need to set
return omaString == string.empty ? new SqlString.Null : new SqlString(omaString);
I have had some fun wrestling matches learning the intricate hand-off between local and outbound types, especially with CLR TVFs.
Hope that can help!

Export to text or excel from MVC controller

What I have already : I have controller code churning up some values / calculations and sending them to the View. Right now, I am displaying all results on the view page.
What I am trying to do : Export those results that are displayed on the view to a text or excel file on press of a button "Export"
Using : MVC
Sample code I have
Controller:
public ActionResult Calculations()
{
dynamic CalcModel = new ExpandoObject();
int var1 = //Value calculated here
int var2 = //Calculation
CalcModel.Var1= var1;
CalcModel.Var2= var2;
return View(CalcModel);
}
View:
<table>
<tr><td>First Value:</td><td><%=Model.Var1%></td></tr>
<tr><td>Second Value:</td><td><%=Model.Var2%></td></tr>
</table>
I want to be able to write these values from the controller to a text file or excel file and let the user save the file. Thanks for the help.
EDIT:
I found a solution (kind of) but need further help:
Latest Controller code:
public ActionResult Calculations()
{
dynamic CalcModel = new ExpandoObject();
int var1 = //Value calculated here
int var2 = //Calculation
CalcModel.Var1= var1;
CalcModel.Var2= var2;
//Export code.
string csv = "Value1 = " + var1 + "|| Value2 = " + var2;
return File(new System.Text.UTF8Encoding().GetBytes(csv), "text/csv",
"Report.txt");
//Export code end.
return View(CalcModel);
}
This generates a text file with the values printed in it. But How do I get each value printed in a separate line.. right now all values are printed in one flat line.
Envrionment.NewLine should do it:
var builder = new StringBuilder();
//this is probably a loop...
builder.AppendFormat("1,2{0}", Envrionment.NewLine);
builder.AppendFormat("3,4{0}", Envrionment.NewLine);
File(new System.Text.UTF8Encoding().GetBytes(builder.ToString()), "text/csv",
"Report.txt");
Edit:
You can try \n as well.
string csvText = string.Format("First Value,{0}\nSecond Value,{1}",var1, var2);
File(new System.Text.UTF8Encoding().GetBytes(csvText), "text/csv",
"Report.txt");
This might help
http://stephenwalther.com/blog/archive/2008/06/16/asp-net-mvc-tip-2-create-a-custom-action-result-that-returns-microsoft-excel-documents.aspx
Or this:
http://www.codeproject.com/KB/aspnet/Streaming_Excel_ASP_NET.aspx

Naming a text file on CSHTML (Razor)

I have a page with a text area for title input and body input.
Saving a text file with those things is easy, the question is, how can I make the file to be named after whatever was placed in the title input?
I tried this:
#{
var result = "";
if (IsPost)
{
var title = Request["title"];
var body = Request["body"];
var filedata = title + "," + body + Environment.NewLine;
var dataFile = Server.MapPath("/App_Data/Request["title"]");
File.WriteAllText(#dataFile, filedata);
result = "Information saved.";
}
}
(Note that var title = Request["title"]; means that its requesting from a text input named "title"). What I want to get is that the input will also be the name of the file its saving.
But it seems that this area:
var dataFile = Server.MapPath("/App_Data/Request["title"]");
is not the correct way.
What is the correct way to do it?
Couple of pointers; firstly this sort of logic should be in a Controller, not in a View. Your Views are supposed to display information about your model, your Controllers carry out operations.
Secondly, the following should do the trick (in a Controller!):
[HttpPost]
public ActionResult SaveFile(string title, string body)
{
var fileData = title + "," + body + Environment.NewLine;
var fileSavePath = Path.Combine(
Server.MapPath("~/TextFiles"),
title.Replace(" ", "_") + ".txt");
File.WriteAllText(fileSavePath, fileData);
return this.RedirectToAction("SaveSuccessful");
}
Of note:
Server.MapPath("~/TextFiles") gives you the path to a TextFiles directory in the root of your web application where the files will be stored.
I've replaced spaces in the title which has been input with underscores.
This method redirects the user to an Action named SaveSuccessful on the same Controller
Of course you need error handling and all sorts of other things in there, but hopefully that helps.

Resources