MVC Razor Rendering controls dynamically - asp.net-mvc-3

This is one way I've found to render controls dynamically with ASP.NET MVC 3 Razor. This is giving me correct data, but I'm curious if anyone sees any red flags with this method, or a painfully more obvious way to do this.
#using (Html.BeginForm())
{
foreach (var item in Model)
{
<tr>
<td>
#item.app_name
</td>
<td>
#item.setting_name
</td>
<td>
#item.setting_description
</td>
<td>
#if (item.data_type == "Bit")
{
#Html.CheckBox("setting_value", item.setting_value == "1" ? true : false)
}
else
{
#Html.TextBox("setting_value", item.setting_value)
}
</td>
<td>
#item.setting_value
</td>
</tr>
}
}

You could use Editor and Display Templates instead...
Check out this link:
http://blogs.msdn.com/b/nunos/archive/2010/02/08/quick-tips-about-asp-net-mvc-editor-templates.aspx

What do editor templates have to do with dynamically creating controls?
What if you need to drive a UI/View from settings in a database, for example?

Related

When using AjaxHelper to retrieve a partial view, the embedded data is always the same

We use ASP.NET MVC 5's AjaxHelper and Ajax.BeginForm to request a partial view. That request also needs some JSON data in order to update a map control.
The view rendering part of the process works great (a table body is replaced with the strongly-typed partial view), but the JSON data (embedded into the data-json attribute of the div element as described in this answer and retrieved in my OnSuccess function) always has the same value.
To eliminate the controller code or ViewBag as culprit, I replaced the JSON data (originally retrieved from the ViewBag) with a direct call to DateTime.Now. Sure enough, the same DateTime is printed each time in updateMap() (e.g., 2/11/2016+5:24:42+PM)
I've tried disabling caching, and changing the HTML method to Post, in my AjaxOptions.
In the Parent View (changing the ListBox selection submits the form):
#model string
#{
ViewBag.Title = "Project List";
AjaxOptions ajaxOpts = new AjaxOptions
{
UpdateTargetId = "tableBody",
OnSuccess = "updateMap",
HttpMethod = "Post",
AllowCache = false
};
}
#using (Ajax.BeginForm("GetProjectsData", ajaxOpts))
{
<fieldset>
<legend>Project State</legend>
<div class="editor-field">
#Html.ListBox("selectedStates", ViewBag.StatesList as MultiSelectList,
new { #class = "chzn-select", data_placeholder = "Choose States...", style = "width:350px;", onchange = "$(this.form).submit();" })
</div>
</fieldset>
}
<table class="table">
<thead>
<tr>
<th>
Project Name
</th>
<th>
Project Firm
</th>
<th>
Project Location
</th>
<th>
Building Type
</th>
<th>
Project Budget
</th>
<th></th>
</tr>
</thead>
<tbody id="tableBody">
#Html.Action("GetProjectsData", new { selectedStates = Model })
</tbody>
</table>
<script>
function updateMap() {
var jsonData = $("#geoJsonData").attr("data-json");
var decoded = decodeURIComponent(jsonData);
console.log(decoded); // always prints same value
}
</script>
The partial view:
#model IEnumerable<OurModel>
<div id="geoJsonData" data-json="#Url.Encode(DateTime.Now.ToString())"></div>
#foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.NAME)
</td>
<td>
#Html.DisplayFor(modelItem => item.COMPANY_NAME)
</td>
<td>
#Html.DisplayFor(modelItem => item.STATE)
</td>
<td>
#Html.DisplayFor(modelItem => item.BUILDING_TYPE)
</td>
<td>
#Html.DisplayFor(modelItem => item.BUDGET_AMT)
</td>
</tr>
}
I'm hesitant to jettison the MVC helper classes' pattern of returning a partial view and instead manually render a view into a JSON object. Why is the updated tablebody visible on screen, but when jQuery requests the div element it always has the same data?
Interesting...replacing the div with a good old hidden input element worked. Now fresh data is retrieved each time.
This
<div id="geoJsonData" data-json="#Url.Encode(DateTime.Now.ToString())"></div>
Became this
<input id="geoJsonData" type="hidden" value="#Url.Encode(DateTime.Now.ToString())" />
I wonder why the data-json in the div remained "stale" while the value of the input field did the trick?

How to Display Conditional Plain Text with Razor

I am having issues with displaying (rather NOT displaying) plain text in an else block.
if (Model.CareerFields != null && ViewBag.CFCount > 0)
{
<h3>Careerfields Listing</h3>
<table>
<tr>
<th></th>
<th>Careerfield Name</th>
</tr>
#foreach (var item in Model.CareerFields)
{
<tr>
<td>
#Html.ActionLink("Select", "Index", new { careerFieldID = item.CareerFieldId })
</td>
<td>
#item.CareerFieldName
</td>
</tr>
}
</table>
}
else
{
No Careerfields associated with #ViewBag.SelectedDivisionTitle
}
The if blocks works fine. The text only renders when true. However, the else block text renders when the page loads, not if it evaluates to false only.
I've tried using
Hmtl.Raw("No Careerfields associated with ")
<text>No Careerfields associated with #ViewBag.SelectedDivisionTitle</text>
#:No Careerfields associated with #ViewBag.SelectedDivisionTitle
But it still renders the plaintext before evaluation.
Any suggestions?
Put your "plain text" inside of a naked <span> tag:
else
{
<span>No Careerfields associated with #ViewBag.SelectedDivisionTitle</span>
}
The browser shouldn't render it special (unless you have css selecting every span) and it'll help razor sense the end of the C# and print your HTML.
The following code worked perfectly for me:
#if (false) {
<h3>
Careerfields Listing
</h3>
<table>
<tr>
<th>
</th>
<th>
Careerfield Name
</th>
</tr>
</table>
}
else
{
#:No Careerfields associated with #ViewBag.SelectedDivisionTitle
}
You can see that the contents of if are rendered when you change condition to true.
Looks like you've forgotten the # sign before your if statement. Try this:
#if (Model.CareerFields != null && ViewBag.CFCount > 0)
{
<h3>Careerfields Listing</h3>
<table>
<tr>
<th></th>
<th>Careerfield Name</th>
</tr>
#foreach (var item in Model.CareerFields)
{
<tr>
<td>
#Html.ActionLink("Select", "Index", new { careerFieldID = item.CareerFieldId })
</td>
<td>#item.CareerFieldName</td>
</tr>
}
</table>
}
else
{
<text>No Careerfields associated with #ViewBag.SelectedDivisionTitle</text>
}
The most concise and correct answer is:
Prepend #: before the text.
(note the : after the #)
This still allows to embed variables in the text by prepending an # to the variable name:
#if (someCondition)
{
#:Some text you want to see.
}
else
{
#:Some other text, with a variable #someVariable included in the text.
}

append two IEnumerable items

IEnumerable<Addresses> AddressSet1=myServices.GetAddresses(LocationId1);
IEnumerable<Addresses> AddressSet2=myServices.GetAddresses(LocationId2);
I want to combine the above two AddressSets
I tried IEnumerable<Addresses> AllAddresses=AddressSet1.Concat(AddressSet2)
But after this when I try to access items from IEnumerable AllAddresses by on my razor view
#if(!myHelper.IsNullorEmpty(model.AllAddresses )
{
#Html.EditorFor(model => model.AllAddresses )
}
and I am getting errors -- Illegal characters in path .Any suggestions to identify cause of this error ?
If I am trying to run my page with out the Concat I am able see the records in AddressSet1 /AddressSet2 displayed on the page .But when I try to combine the two to form I Enumerable AllAddresses ,it is throwing errors please help
pasted below is my Editor Template
#model MyServiceRole.Models.Addresses
#{
ViewBag.Title = "All addresses Items";
}
<table>
<tr>
<td>
<span>Index</span>
</td>
<td>
</tr>
<tr>
<td>Address XID</td>
<td>
#Html.EditorFor(model => model.AddressID)
</td>
</tr>
<tr>
<td>Title</td>
<td>
#Html.EditorFor(model => model.Title)
</td>
</tr>
<tr>
<td>Description</td>
<td>
#Html.EditorFor(model => model.Description)
</td>
</tr>
<tr>
<td>Image URL</td>
<td>
#Html.EditorFor(model => model.Photo.URL)
</td>
</tr>
</table>
I tested your issue and ran into the same problem.
List<string> a = new List<string>{ "a" };
List<string> b = new List<string>{ "b" };
IEnumerable<string> concat = a.Concat<string>(b);
foreach(string s in concat) { } // this works
return View(concat);
In view:
#model IEnumerable<string>
#foreach(string s in Model) //This blows up
{
}
#Html.EditorFor(m => Model) //Also blows up
It looks like you honestly can't use templates with or enumerate over the
System.Linq.Enumerable.ConcatIterator<T>
class that Concat creates within a View. This seems like a bug.
Anyway adding .ToList() fixes your issue.
return View(concat.ToList());
If you want to use editor templates why are you writing foreach loops? You don't need this loop at all. Simply write the following and get rid of the foreach:
#Html.EditorFor(x => x.AllAddresses)
and then you will obviously have a corresponding editor template that ASP.NET MVC will automatically render for each element of the AllAddresses collection so that you don't need to write any foreach loops in your view (~/Views/Shared/EditorTemplates/Address.cshtml):
#model Address
...

Use Html.RadioButtonFor and Html.LabelFor for the same Model but different values

I have this Razor Template
<table>
<tr>
<td>#Html.RadioButtonFor(i => i.Value, "1")</td>
<td>#Html.LabelFor(i => i.Value, "true")</td>
</tr>
<tr>
<td>#Html.RadioButtonFor(i => i.Value, "0")</td>
<td>#Html.LabelFor(i => i.Value, "false")</td>
</tr>
</table>
That gives me this HTML
<table>
<tr>
<td><input id="Items_1__Value" name="Items[1].Value" type="radio" value="1" /></td>
<td><label for="Items_1__Value">true</label></td>
</tr>
<tr>
<td><input checked="checked" id="Items_1__Value" name="Items[1].Value" type="radio" value="0" /></td>
<td><label for="Items_1__Value">false</label></td>
</tr>
</table>
So I have the ID Items_1__Value twice which is - of course - not good and does not work in a browser when I click on the second label "false" the first radio will be activated.
I know I could add an own Id at RadioButtonFor and refer to that with my label, but that's not pretty good, is it? Especially because I'm in a loop and cannot just use the name "value" with an added number, that would be end up in multiple Dom Ids in my final HTML markup as well.
Shouldn't be a good solution for this?
Don't over-engineer a solution for this. All you are trying to accomplish is to have the radio buttons respond to clicks on the text. Keep it simple and just wrap your radio buttons in label tags:
<table>
<tr>
<td><label>#Html.RadioButtonFor(i => i.Value, "1")True</label></td>
</tr>
<tr>
<td><label>#Html.RadioButtonFor(i => i.Value, "0")False</label></td>
</tr>
</table>
The LabelFor html helper is usually used to bring in the Name from the Display attribute on your View Model (e.g. "[Display(Name = "Enter your Name")]).
With radio buttons, the name isn't particularly useful, because you have a different line of text for each radio button, meaning you are stuck hard coding the text into your view anyway.
I've been wondering how MVC determines "nested" field names and IDs. It took a bit of research into the MVC source code to figure out, but I think I have a good solution for you.
How EditorTemplates and DisplayTemplates determine field names and IDs
With the introduction of EditorTemplates and DisplayTemplates, the MVC framework added ViewData.TemplateInfo that contains, among other things, the current "field prefix", such as "Items[1].". Nested templates use this to create unique names and IDs.
Create our own unique IDs:
The TemplateInfo class contains an interesting method, GetFullHtmlFieldId. We can use this to create our own unique IDs like so:
#{string id = ViewData.TemplateInfo.GetFullHtmlFieldId("fieldName");}
#* This will result in something like "Items_1__fieldName" *#
For The Win
Here's how to achieve the correct behavior for your example:
<table>
<tr>
#{string id = ViewData.TemplateInfo.GetFullHtmlFieldId("radioTrue");}
<td>#Html.RadioButtonFor(i => i.Value, "1", new{id})</td>
<td>#Html.LabelFor(i => i.Value, "true", new{#for=id})</td>
</tr>
<tr>
#{id = ViewData.TemplateInfo.GetFullHtmlFieldId("radioFalse");}
<td>#Html.RadioButtonFor(i => i.Value, "0", new{id})</td>
<td>#Html.LabelFor(i => i.Value, "false", new{#for=id})</td>
</tr>
</table>
Which will give you the following HTML:
<table>
<tr>
<td><input id="Items_1__radioTrue" name="Items[1].Value" type="radio" value="1" /></td>
<td><label for="Items_1__radioTrue">true</label></td>
</tr>
<tr>
<td><input checked="checked" id="Items_1__radioFalse" name="Items[1].Value" type="radio" value="0" /></td>
<td><label for="Items_1__radioFalse">false</label></td>
</tr>
</table>
Disclaimer
My Razor syntax is underdeveloped, so please let me know if this code has syntax errors.
For what its worth
It's pretty unfortunate that this functionality isn't built-in to RadioButtonFor. It seems logical that all rendered Radio Buttons should have an ID that is a combination of its name AND value, but that's not the case -- maybe because that would be different from all other Html helpers.
Creating your own extension methods for this functionality seems like a logical choice, too. However, it might get tricky using the "expression syntax" ... so I'd recommend overloading .RadioButton(name, value, ...) instead of RadioButtonFor(expression, ...). And you might want an overload for .Label(name, value) too.
I hope that all made sense, because there's a lot of "fill in the blanks" in that paragraph.
#Scott Rippey nearly has it, but i guess he must be using a different version of MVC3 to me because for me #Html.LabelFor has no overloads that will take 3 arguments. I found that using the normal #Html.Label works just fine:
#{string id = ViewData.TemplateInfo.GetFullHtmlFieldId("radioButton_True");}
#Html.Label(id, "True:")
#Html.RadioButtonFor(m => m.radioButton, true, new { id })
#{id = ViewData.TemplateInfo.GetFullHtmlFieldId("radioButton_False");}
#Html.Label(id, "False:")
#Html.RadioButtonFor(m => m.radioButton, false, new { id })
this allows you to click on the label and select the associated radiobutton as you'd expect.
Here's an HtmlHelper you can use, though you may with to customize it. Only barely tested, so YMMV.
public static MvcHtmlString RadioButtonWithLabelFor<TModel, TProperty>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TProperty>> expression, object value, object htmlAttributes = null)
{
var name = ExpressionHelper.GetExpressionText(expression);
var id = helper.ViewData.TemplateInfo.GetFullHtmlFieldId(name + "_" + value);
var viewData = new ViewDataDictionary(helper.ViewData) {{"id", id}};
if (htmlAttributes != null)
{
var viewDataDictionary = HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes);
foreach (var keyValuePair in viewDataDictionary)
{
viewData[keyValuePair.Key] = keyValuePair.Value;
}
}
var radioButton = helper.RadioButtonFor(expression, value, viewData);
var tagBuilder = new TagBuilder("label");
tagBuilder.MergeAttribute("for", id);
tagBuilder.InnerHtml = value.ToString();
return new MvcHtmlString(radioButton.ToHtmlString() + tagBuilder.ToString());
}
Not Perfect but work though,
<table>
<tr>
<td>#ReplaceName(Html.RadioButtonFor(i => i.Value, "1"))</td>
<td>#Html.LabelFor(i => i.Value[0], "true")</td>
</tr>
<tr>
<td>#ReplaceName(Html.RadioButtonFor(i => i.Value, "0"))</td>
<td>#Html.LabelFor(i => i.Value[1], "false")</td>
</tr>
</table>
#functions {
int counter = 0;
MvcHtmlString ReplaceName(MvcHtmlString html){
return MvcHtmlString.Create(html.ToString().Replace("__Value", "__Value_" + counter++ +"_"));
}
}
You can add text with tags
<td>#Html.RadioButtonFor(i => i.Value, true) <text>True</text></td>
<td>#Html.RadioButtonFor(i => i.Value, false) <text>False</text></td>
Apparently there is a good solution
<td>#Html.RadioButtonFor(i => i.Value, true)</td>
<td>#Html.RadioButtonFor(i => i.Value, false)</td>

ASP.NET MVC 3: Using Enumerable extension methods in the view

Given the following Razor Partial View and understanding that Product is an NHibernate mapped object so the calls to IEnumerable here will fire database queries (when not cached).
Is this bad practice? Should I be providing a flatter view of my data for this view so that I can make these calls in my controller/business logic?
#model IEnumerable<MyProject.Data.Models.Product>
<table>
<tr>
<th></th>
<th>Total Orders</th>
<th>Fulfilled</th>
<th>Returned</th>
<th>In stock</th>
</tr>
#foreach (var product in Model) {
<tr>
<td>
#Html.ActionLink(product .Name, "Detail", "Product", new { id = product.Id }, null)
</td>
<td>
#product.Orders.Count
</td>
<td>
#product.Orders.Where(x=>x.Fulfilled).Count()
</td>
<td>
#product.Orders.Where(x=>x.Returned).Count()
</td>
<td>
#(product.Stock.Count - product.Orders.Count)
</td>
</tr>
}
</table>
Is this bad practice?
Yes.. In fact it's breaking the MVC pattern - the View's should not call back through the model, only receive in order to do it's sole job: rendering HTML.
If you need additional information than just the one entity, populate a ViewModel with all the information you need, then pass that to your View.
Also, don't loop through the IEnumerable in the model, use a Display Template:
#Html.DisplayForModel()
The advantage of this is no explicit loop, taking advantage of MVC conventions, and adhering to model hierachy when model binding.

Resources