I've got the code below where I am checking for a default value in an options list. It works, but it's ugly if/else logic. The quotes have me stumped in how to optimize to be cleaner C# code. Looking for a way to make it nicer, perhaps even just one clean line of code.
#foreach (var myValue in ratingControlValues)
{
if (myValue.Equals(ratingControlInitialValue))
{
<option value="#myValue" selected='selected'>#myValue</option>
}
else
{
<option value="#myValue" >#myValue</option>
}
}
Consider using The Select Tag Helper
In your controller you can assign the options to a property of your view model or view bag
var ratings = ratingControlValues
.Select(myValue => new SelectListItem {
Value = myValue,
Text = myValue,
Selected = myValue.Equals(ratingControlInitialValue)
}).ToList();
ViewBag.RatingsOptions = ratings;
The above example sets the values using the ViewBag
This will now allow the view to be simplified using the tag-helper
<select asp-for="Ratings" asp-items="ViewBag.RatingsOptions"></select>
to a simple single line of markup
I have a view that uses the next Model
#model Merak.Models.Product.Options.NumberOfObjectsProductOptionModel
And 2 radiobuttons
#Html.RadioButton(Constants.HtmlControlValues.OptionNumberObjectSelect, #Model.OptionOnePrice, true) <br/>
#Html.RadioButton(Constants.HtmlControlValues.OptionNumberObjectSelect, #Model.OptionTwoPrice)
Inside constants.HtmlControlValues.OptionNumberObjectSelect is a string with "groupname" inside.
I would think that the Html control would generate something like:
<input id="groupname" name="groupname" type="radio" value="50,00">
But instead it generates something like:
<input id="NumberOfObjectsProductOptionModel_groupname" name="NumberOfObjectsProductOptionModel.groupname" type="radio" value="50,00">
Any idea why this behaviour is happening and what I can do to get the short name/id version?
You can assign the constants.HtmlControlValues.OptionNumberObjectSelect to a variable a then get the value:
#model Merak.Models.Product.Options.NumberOfObjectsProductOptionModel
#{
string myControl = constants.HtmlControlValues.OptionNumberObjectSelect
}
And then use it in your control:
#Html.RadioButton(#myControl, #Model.OptionOnePrice, true)
Could you use #Html.RadioButtonFor(model => Model.OptionOnePrice) and see if that works better. That way it's bound to your model.
I'm wondering what the best practice is to select an option from a select field from my database.
I am pulling the data in from my model, but it seems like having an if in every line of code isnt the most efficient.
Here is my current code, is there a better way?
<select id="Downloads" name="Downloads">
<option value="Option1" <% if(Model.Downloads == "Option1"){ %>selected <% } %>>Option1</option>
<option value="Option2" <% if(Model.Downloads == "Option2"){ %>selected <% } %>>Option2</option>
<option value="Option3" <% if(Model.Downloads == "Option3"){ %>selected <% } %>>Option3</option>
</select>
I have 10 of these select boxes and just want to keep my code clean
Build a SelectList, or a collection of SelectListItems on your model, and then use use DropdownListFor:
#Html.DropDownListFor(x => x.Downloads, Model.DownloadOptions)
I suggest you add a css class to each select box.Then create an javascript array to save value of them. Following is a way to retrieve value of them and push them into javascript array.
var values =[];
$(".mySelectBox").each(function(i) {
//push to values array
});
In Razor view I have a Javascript function. This function take 2 URLS String in arguments and call AJAX to do operation.
When I generated Url string in Razor, Razor change the URLS. Like changed & to & and damage my query strings which used in my URL address. Also Html.Raw() has not work in this case.
What can I do ?
EXAMPLE:
In my Razor editor:
<a href="#" style="color:#0564c1;" onclick="PopUpStart('POST','','',200,100,'#(Html.Raw(address+"/index/?id="+baseObject.Id+"&"+"type="+dataTypeInt))','#Html.Raw(address + "/cancel/?id="+baseObject.Id+"&type="+dataTypeInt )','ReloadPage',true);return false;">
Edit
</a>
In result :
<a href="#" style="color:#0564c1;" onclick="PopUpStart('POST','','',200,100,'/PdfInstanceEdit/index/?id=1&type=270','/PdfInstanceEdit/cancel/?id=1`&`type=270','ReloadPage',true);return false;">
Edit
</a>
The URL address like :
address+"/index/?id="+baseObject.Id+"&"+"type="+dataTypeInt
Change to :
/PdfInstanceEdit/index/?id=1&type=270
In other world character & => &
Its usually a bad idea to try and combine server code and client strings inside the quotes of a property (ie onclick="something#(something())" )
Its better to just return the entire lot in a server side function
Here's how I would rework your code:
<a href="#" style="color:#0564c1;"
onclick="#Html.Raw(
String.Format(
"PopUpStart('POST','','',200,100,'{0}','{1}','ReloadPage',true);return false;"
, Url.Action("index",address,new{id = baseObject.Id, type = dataTypeInt})
, Url.Action("cancel",address,new{id = baseObject.Id, type = dataTypeInt})
)
)"/>
Edit
</a>
Also note the difference between #(Html.Raw()) and #Html.Raw() - you should use the latter!
As direct assignment of events such as onClick is frowned on these days, a better way to accomplish then may be through js:
Add a hidden field for Id and dataTypeInt to your page:
#Html.HiddenFor(model=> model.Id)
#Html.Hidden("dataTypeInt ", dataTypeInt)
Add an id to your anchor:
Edit
Then your script:
<script>
$(document).ready(function () {
readyLinks();
});
readyLinks = function(){
var id = $('#Id).val();
var dataType = $('#dataTypeInt').val();
var indexUrl = '/PdfInstanceEdit/index?id=' + id + '&type=' + dataType;
var cancelUrl = '/PdfInstanceEdit/cancel?id=' + id + '&type=' + dataType;
$('#editLink).on('click', function(){
PopUpStart('POST','','',200,100,indexUrl, cancelUrl,'ReloadPage',true);
return false;
});
};
</script>
You should use Html.Raw() as suggested in the comments, see the documentation.
As described in this thread, if you have a particular problem with the output encoded format, you could use the HttpUtility.HtmlDecode() function, see documentation.
#Html.Raw(HttpUtility.HtmlDecode(address+"/index/?id="+baseObject.Id+"&"+"type="+dataTypeInt))
But since this could be a solution I cannot address you problem precisely...
A friendly reminder: if you're trying to put a Javascript string inside an HTML attribute, the value must be encoded twice. It must first be Javascript-encoded, then that result must be HTML-encoded. You could inadvertently open an XSS hole in your site if you don't perform both encodings in the correct order.
Say you have a string s that you want to display to the client. You'd write your Razor markup as:
Click me
Note the explicit call to JavaScriptStringEncode. Then Razor's # syntax will auto-HtmlEncode this value before writing it to the response.
I have a simple field in one of my views that shows a sum for one of my columns using this code:
<p class="points-total" >#Html.Encode(ViewData["pointsTotal"])</p>
This is my controller code regarding pointsTotal:
pointsTotal = occurrences.Sum(o => o.Points);
ViewData["pointsTotal"] = pointsTotal.ToString();
I would like to assign a different class to this line based on the value of pointsTotal. For example if the total is over 50 points I'd like to assign it to class points-total-fifty.
I know I can do this on other HTML helpers like DisplayFor by doing this:
<p class="#(item.Total > 50 ? "points-total-fifty" :
"points-total")">#Html.DisplayFor(modelItem => item.Total)</p>
Is there a way to do the same thing with the Html.Encode helper?
Actually the code you put for your second example will work also with the Html.Encode helper as you are styling the <p> element. One way to do it for example:
#{
string cssClass = "points-total";
int? total = ViewData["pointsTotal"] as int?;
if (total.HasValue && total > 50)
{
cssClass = "points-total-fifty";
}
}
<p class="#cssClass" >#Html.Encode(ViewData["pointsTotal"])</p>