ASP.NET MVC partial views: input name prefixes - asp.net-mvc
Suppose I have ViewModel like
public class AnotherViewModel
{
public string Name { get; set; }
}
public class MyViewModel
{
public string Name { get; set; }
public AnotherViewModel Child { get; set; }
public AnotherViewModel Child2 { get; set; }
}
In the view I can render a partial with
<% Html.RenderPartial("AnotherViewModelControl", Model.Child) %>
In the partial I'll do
<%= Html.TextBox("Name", Model.Name) %>
or
<%= Html.TextBoxFor(x => x.Name) %>
However, the problem is that both will render name="Name" while I need to have name="Child.Name" in order for model binder to work properly. Or, name="Child2.Name" when I render the second property using the same partial view.
How do I make my partial view automatically recognize the required prefix? I can pass it as a parameter but this is too inconvenient. This is even worse when I want for example to render it recursively. Is there a way to render partial views with a prefix, or, even better, with automatic reconition of the calling lambda expression so that
<% Html.RenderPartial("AnotherViewModelControl", Model.Child) %>
will automatically add correct "Child." prefix to the generated name/id strings?
I can accept any solution, including 3-rd party view engines and libraries - I actually use Spark View Engine (I "solve" the problem using its macros) and MvcContrib, but did not find a solution there. XForms, InputBuilder, MVC v2 - any tool/insight that provide this functionality will be great.
Currently I think about coding this myself but it seems like a waste of time, I can't believe this trivial stuff is not implemented already.
A lot of manual solutions may exists, and all of them are welcome. For example, I can force my partials to be based off IPartialViewModel<T> { public string Prefix; T Model; }. But I'd rather prefer some existing/approved solution.
UPDATE: there's a similar question with no answer here.
You can extend Html helper class by this :
using System.Web.Mvc.Html
public static MvcHtmlString PartialFor<TModel, TProperty>(this HtmlHelper<TModel> helper, System.Linq.Expressions.Expression<Func<TModel, TProperty>> expression, string partialViewName)
{
string name = ExpressionHelper.GetExpressionText(expression);
object model = ModelMetadata.FromLambdaExpression(expression, helper.ViewData).Model;
var viewData = new ViewDataDictionary(helper.ViewData)
{
TemplateInfo = new System.Web.Mvc.TemplateInfo
{
HtmlFieldPrefix = name
}
};
return helper.Partial(partialViewName, model, viewData);
}
and simply use it in your views like this :
<%= Html.PartialFor(model => model.Child, "_AnotherViewModelControl") %>
and you will see everything is ok!
so far, i was searching for the same thing I have found this recent post:
http://davybrion.com/blog/2011/01/prefixing-input-elements-of-partial-views-with-asp-net-mvc/
<% Html.RenderPartial("AnotherViewModelControl", Model.Child, new ViewDataDictionary
{
TemplateInfo = new System.Web.Mvc.TemplateInfo { HtmlFieldPrefix = "Child1" }
})
%>
My answer, based on the answer of Mahmoud Moravej including the comment of Ivan Zlatev.
public static MvcHtmlString PartialFor<TModel, TProperty>(this HtmlHelper<TModel> helper, System.Linq.Expressions.Expression<Func<TModel, TProperty>> expression, string partialViewName)
{
string name = ExpressionHelper.GetExpressionText(expression);
object model = ModelMetadata.FromLambdaExpression(expression, helper.ViewData).Model;
StringBuilder htmlFieldPrefix = new StringBuilder();
if (helper.ViewData.TemplateInfo.HtmlFieldPrefix != "")
{
htmlFieldPrefix.Append(helper.ViewData.TemplateInfo.HtmlFieldPrefix);
htmlFieldPrefix.Append(name == "" ? "" : "." + name);
}
else
htmlFieldPrefix.Append(name);
var viewData = new ViewDataDictionary(helper.ViewData)
{
TemplateInfo = new System.Web.Mvc.TemplateInfo
{
HtmlFieldPrefix = htmlFieldPrefix.ToString()
}
};
return helper.Partial(partialViewName, model, viewData);
}
Edit:
The Mohamoud's answer is incorrect for nested partial rendering. You need to append the new prefix to the old prefix, only if it is necessary. This was not clear in the latest answers (:
Using MVC2 you can achieve this.
Here is the strongly typed view:
<%# Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<MvcLearner.Models.Person>" %>
<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
Create
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<h2>Create</h2>
<% using (Html.BeginForm()) { %>
<%= Html.LabelFor(person => person.Name) %><br />
<%= Html.EditorFor(person => person.Name) %><br />
<%= Html.LabelFor(person => person.Age) %><br />
<%= Html.EditorFor(person => person.Age) %><br />
<% foreach (String FavoriteFoods in Model.FavoriteFoods) { %>
<%= Html.LabelFor(food => FavoriteFoods) %><br />
<%= Html.EditorFor(food => FavoriteFoods)%><br />
<% } %>
<%= Html.EditorFor(person => person.Birthday, "TwoPart") %>
<input type="submit" value="Submit" />
<% } %>
</asp:Content>
Here is the strongly typed view for the child class (which must be stored in a subfolder of the view directory called EditorTemplates):
<%# Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<MvcLearner.Models.TwoPart>" %>
<%= Html.LabelFor(birthday => birthday.Day) %><br />
<%= Html.EditorFor(birthday => birthday.Day) %><br />
<%= Html.LabelFor(birthday => birthday.Month) %><br />
<%= Html.EditorFor(birthday => birthday.Month) %><br />
Here is the controller:
public class PersonController : Controller
{
//
// GET: /Person/
[AcceptVerbs(HttpVerbs.Get)]
public ActionResult Index()
{
return View();
}
[AcceptVerbs(HttpVerbs.Get)]
public ActionResult Create()
{
Person person = new Person();
person.FavoriteFoods.Add("Sushi");
return View(person);
}
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create(Person person)
{
return View(person);
}
}
Here are the custom classes:
public class Person
{
public String Name { get; set; }
public Int32 Age { get; set; }
public List<String> FavoriteFoods { get; set; }
public TwoPart Birthday { get; set; }
public Person()
{
this.FavoriteFoods = new List<String>();
this.Birthday = new TwoPart();
}
}
public class TwoPart
{
public Int32 Day { get; set; }
public Int32 Month { get; set; }
}
And the output source:
<form action="/Person/Create" method="post"><label for="Name">Name</label><br />
<input class="text-box single-line" id="Name" name="Name" type="text" value="" /><br />
<label for="Age">Age</label><br />
<input class="text-box single-line" id="Age" name="Age" type="text" value="0" /><br />
<label for="FavoriteFoods">FavoriteFoods</label><br />
<input class="text-box single-line" id="FavoriteFoods" name="FavoriteFoods" type="text" value="Sushi" /><br />
<label for="Birthday_Day">Day</label><br />
<input class="text-box single-line" id="Birthday_Day" name="Birthday.Day" type="text" value="0" /><br />
<label for="Birthday_Month">Month</label><br />
<input class="text-box single-line" id="Birthday_Month" name="Birthday.Month" type="text" value="0" /><br />
<input type="submit" value="Submit" />
</form>
Now this is complete. Set a breakpoint in the Create Post controller action to verify. Don't use this with lists however because it wont work. See my question on using EditorTemplates with IEnumerable for more on that.
This is an old question, but for anyone arriving here looking for a solution, consider using EditorFor, as suggested in a comment in https://stackoverflow.com/a/29809907/456456. To move from a partial view to an editor template, follow these steps.
Verify that your partial view is bound to ComplexType.
Move your partial view to a subfolder EditorTemplates of the current view folder, or to the folder Shared. Now, it is an editor template.
Change #Html.Partial("_PartialViewName", Model.ComplexType) to #Html.EditorFor(m => m.ComplexType, "_EditorTemplateName"). The editor template is optional if it's the only template for the complex type.
Html Input elements will automatically be named ComplexType.Fieldname.
PartailFor for asp.net Core 2 in case someone needs it.
public static ModelExplorer GetModelExplorer<TModel, TResult>(this IHtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TResult>> expression)
{
if (expression == null)
throw new ArgumentNullException(nameof(expression));
return ExpressionMetadataProvider.FromLambdaExpression(expression, htmlHelper.ViewData, htmlHelper.MetadataProvider);
}
public static IHtmlContent PartialFor<TModel, TResult>(this IHtmlHelper<TModel> helper, Expression<Func<TModel, TResult>> expression, string partialViewName, string prefix = "")
{
var modelExplorer = helper.GetModelExplorer(expression);
var viewData = new ViewDataDictionary(helper.ViewData);
viewData.TemplateInfo.HtmlFieldPrefix += prefix;
return helper.Partial(partialViewName, modelExplorer.Model, viewData);
}
As stated here: https://stackoverflow.com/a/58943378/3901618 - for ASP.NET Core - you can use the partial tag helper.
<partial name="AnotherViewModelControl" for="Child" />
<partial name="AnotherViewModelControl" for="Child2" />
It generates all required name prefixes.
I came across this issue also and after much pain i found it was easier to redesign my interfaces such that i didn't need to post back nested model objects. This forced me to change my interface workflows: sure i now require the user to do in two steps what i dreamed of doing on one, but the usability and code maintainability of the new approach is of greater value to me now.
Hope this helps some.
You could add a helper for the RenderPartial which takes the prefix and pops it in the ViewData.
public static void RenderPartial(this HtmlHelper helper,string partialViewName, object model, string prefix)
{
helper.ViewData["__prefix"] = prefix;
helper.RenderPartial(partialViewName, model);
}
Then a further helper which concatenates the ViewData value
public static void GetName(this HtmlHelper helper, string name)
{
return string.Concat(helper.ViewData["__prefix"], name);
}
and so in the view ...
<% Html.RenderPartial("AnotherViewModelControl", Model.Child, "Child.") %>
in the partial ...
<%= Html.TextBox(Html.GetName("Name"), Model.Name) %>
Like you, I add Prefix property (a string) to my ViewModels which I append before my model bound input names. (YAGNI preventing the below)
A more elegant solution might be a base view model that has this property and some HtmlHelpers that check if the view model derives from this base and if so append the prefix to the input name.
Hope that helps,
Dan
How about just before you call RenderPartial you do
<% ViewData["Prefix"] = "Child."; %>
<% Html.RenderPartial("AnotherViewModelControl", Model.Child) %>
Then in your partial you have
<%= Html.TextBox(ViewData["Prefix"] + "Name", Model.Name) %>
Related
Asp.net mvc 2 templates without prefix
Given following view model: class DetailsViewModel { public HeaderViewModel Header {get;set;} public FooterViewModel Footer {get;set;} } I'm using editor template for Header view model: <%: Html.EditorFor(x => x.Header) %> The editor template (EditorTemplates/HeaderViewModel.ascx) <%# Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<HeaderViewModel>" %> <% ViewData.TemplateInfo.HtmlFieldPrefix = ""; %> <%: Html.EditorFor(x => x.Search) %> The result: <input type="text" value="" name="Search" id="Search" /> If I remove the line <% ViewData.TemplateInfo.HtmlFieldPrefix = ""; %> the result is: <input type="text" value="" name="Header.Search" id="Header_Search" /> Is there another way to achieve the same - render the names of the control without prefix? I was thinking about a helper: public static MvcHtmlString EditorWithoutPrefix<TModel, TValue>( this HtmlHelper<TModel> html, TValue value) { var htmlHelper =... // create new HtmlHelper<TValue> and set it's model to be 'value' argument return htmlHelper.EditorForModel(); } and use it: <%: Html.EditorWithoutPrefix(Model.Header) %> but it is throwing exceptions. Or maybe you know another elegant way to render names without prefix?
You could use the proper overload: <%: Html.EditorFor(x => x.Search, "SearchViewModel", "") %>
Create Template for complex object
I have an object like this public class Locs { public string City {get; set; } public int Zip {get; set; } } public class Names { public string FirstName {get; set; } public string LastName {get; set; } public Locs[] Locations {get; set; } } For the class Names I am generating strongly typed View based on [Create Template]. But when its generated it only show input controls for FristName and Last Name. How can I create a View that can also get Locations from the html page? So that I can easily save data from submit button. My Form is like this <input type="text" id="FirstName" name="FirstName" /> <input type="text" id="LastName" name="LastName" /> <p> <input type="text" id="City1" name="City1" /> <input type="text" id="Zip1" name="Zip1" /> </p> Add more locations As you can see User can dynamically create City and Zip. I am now sure how many he will create. How can I get such object in my view? Can i get such object automatically? Also I want to apply validations.
If you are trying to show an editor an for each locations, you can loop through the Locations property in your view: Rest of your view... <% for (int i = 0; i < Model.Locations.Count; i++) { %> <%= Html.TextboxFor(model => model.Locations[i].City) %> <%= Html.TextboxFor(model => model.Locations[i].Zip) %> }%> Continue your view.
Asp.net MVC2 ModelBindingContext.ModelName empty
I'm not even quite sure where to start explaining this problem. I've been working on this for about the past 10 hours without a clue as to what the root cause is. If any additional details are needed, I'd be happy to provide. I'm just guessing at what is relevant at this point. I have an MVC2 site with routes set up by by Steve Hodgkiss' wonderful RestfulRouting package, using the default route setup with nested controllers (e.g. /customer/{custid}/location/{locid} and such). In this, I have one particular model that is giving me issues. For some reason, when the create page post's the data back to my server, the ModelName property in the ModelBindingContext object passed to the DefaultModelBinder (well, my custom class inherited from DefaultModelBinder, to handle grabbing objects from a repository). This happens only for this one model. And I can't spot the differences at all. The broken model public class RemedialItem : Entity { public virtual int Id { get; set; } .... A working model: public class Customer : Entity { public virtual int Id { get; set; } .... Entity is just an empty class used as a marker for Reflection use. The broken controller method in RemedialItemController.cs [HttpGet] public ActionResult New(int? locationId, int? applianceId) { var model = ViewModelFactory.Create<CreateRemedialItemViewModel>(); model.Categories = (from c in repository.Query<RemedialItemCategory>() orderby c.Name select c).ToList(); model.RemedialItem = new RemedialItem(); return View(model); } A working controller method in CustomerController.cs [HttpGet] public ActionResult New() { var viewModel = ViewModelFactory.Create<SingleCustomerViewModel>(); viewModel.Customer = new Customer(); return View(viewModel); } ViewModelFactory is an injected class that handles setting up some basic properties common to all view models (mainly is the user logged in and user details right now) A broken viewmodel: public class CreateRemedialItemViewModel : ViewModelBase { public RemedialItem RemedialItem { get; set; } public IList<Location> Locations { get; set; } public IList<Appliance> Appliances { get; set; } public IList<RemedialItemCategory> Categories { get; set; } } A working ViewModel: public class SingleCustomerViewModel : ViewModelBase { public Customer Customer { get; set; } } ViewModelBase contains a handful of properties populated by the ViewModelFactory. The broken form in thew New view for RemedialItem: <% using(Html.BeginForm("Create","RemedialItem",FormMethod.Post)) {%> <%: Html.AntiForgeryToken() %> <fieldset> <legend>General</legend> <div> <%: Html.LabelFor(m=>m.RemedialItem.Category) %> <%:Html.DropDownListFor(m=>m.RemedialItem.Category.Id, new SelectList(Model.Categories,"Id","Name")) %> </div> <div> <%: Html.LabelFor(m=>m.RemedialItem.Item) %> <%: Html.TextAreaFor(m=>m.RemedialItem.Item) %> </div> <div> <%: Html.LabelFor(m=>m.RemedialItem.Note) %> <%: Html.TextAreaFor(m=>m.RemedialItem.Note) %> </div> <input type="submit" value="Create Item" /> </fieldset> <%}%> A working New view: <% using (Html.BeginForm("Create","Customer",FormMethod.Post)) {%> <%: Html.ValidationSummary(true) %> <%:Html.AntiForgeryToken() %> <fieldset> <legend>Fields</legend> <p> <%: Html.LabelFor(m=>m.Customer.Name) %> <%: Html.TextBoxFor(m=>m.Customer.Name) %> </p> <p> <%: Html.LabelFor(m=>m.Customer.Street) %> <%: Html.TextBoxFor(m=>m.Customer.Street) %> </p> [...tl;dr...] <p> <input type="submit" value="Create" /> </p> </fieldset> <% } %> Both produce similar field names: Broken: <label for="RemedialItem_Item">Item</label> <textarea cols="20" id="RemedialItem_Item" name="RemedialItem.Item" rows="2"> </textarea> Working: <label for="Customer_Name">Name</label> <input id="Customer_Name" name="Customer.Name" type="text" value="" /> I apologize for the overly long code dump, in short: The working set of stuff, when posted back on the create form, has the ModelName set to Customer. The broken stuff is an empty string Is there something I'm missing? Has anyone encountered something like this before?
I found the issue. In the ViewModel the property that held the instance of RemedialItem to display was called RemedialItem. In the action it posted to, the parameter that took the RemedialItem instance was called item, and that broke everything. In short, when using ViewModels, make sure the parameter name that takes an object from the ViewModel is the same as the property name in the viewmodel. There went my day.
ASP.NET MVC Checkbox Group
I am trying to formulate a work-around for the lack of a "checkbox group" in ASP.NET MVC. The typical way to implement this is to have check boxes of the same name, each with the value it represents. <input type="checkbox" name="n" value=1 /> <input type="checkbox" name="n" value=2 /> <input type="checkbox" name="n" value=3 /> When submitted, it will comma delimit all values to the request item "n".. so Request["n"] == "1,2,3" if all three are checked when submitted. In ASP.NET MVC, you can have a parameter of n as an array to accept this post. public ActionResult ActionName( int[] n ) { ... } All of the above works fine. The problem I have is that when validation fails, the check boxes are not restored to their checked state. Any suggestions. Problem Code: (I started with the default asp.net mvc project) Controller public class HomeController : Controller { public ActionResult Index() { var t = getTestModel("First"); return View(t); } [AcceptVerbs(HttpVerbs.Post)] public ActionResult Index(TestModelView t) { if(String.IsNullOrEmpty( t.TextBoxValue)) ModelState.AddModelError("TextBoxValue", "TextBoxValue required."); var newView = getTestModel("Next"); return View(newView); } private TestModelView getTestModel(string prefix) { var t = new TestModelView(); t.Checkboxes = new List<CheckboxInfo>() { new CheckboxInfo(){Text = prefix + "1", Value="1", IsChecked=false}, new CheckboxInfo(){Text = prefix + "2", Value="2", IsChecked=false} }; return t; } } public class TestModelView { public string TextBoxValue { get; set; } public List<CheckboxInfo> Checkboxes { get; set; } } public class CheckboxInfo { public string Text { get; set; } public string Value { get; set; } public bool IsChecked { get; set; } } } ASPX <% using( Html.BeginForm() ){ %> <p><%= Html.ValidationSummary() %></p> <p><%= Html.TextBox("TextBoxValue")%></p> <p><% int i = 0; foreach (var cb in Model.Checkboxes) { %> <input type="checkbox" name="Checkboxes[<%=i%>]" value="<%= Html.Encode(cb.Value) %>" <%=cb.IsChecked ? "checked=\"checked\"" : String.Empty %> /><%= Html.Encode(cb.Text)%><br /> <% i++; } %></p> <p><input type="submit" value="submit" /></p> <% } %> Working Code Controller [AcceptVerbs(HttpVerbs.Post)] public ActionResult Index(TestModelView t) { if(String.IsNullOrEmpty( t.TextBoxValue)) { ModelState.AddModelError("TextBoxValue", "TextBoxValue required."); return View(t); } var newView = getTestModel("Next"); return View(newView); } ASPX int i = 0; foreach (var cb in Model.Checkboxes) { %> <input type="checkbox" name="Checkboxes[<%=i%>].IsChecked" <%=cb.IsChecked ? "checked=\"checked\"" : String.Empty %> value="true" /> <input type="hidden" name="Checkboxes[<%=i%>].IsChecked" value="false" /> <input type="hidden" name="Checkboxes[<%=i%>].Value" value="<%= cb.Value %>" /> <input type="hidden" name="Checkboxes[<%=i%>].Text" value="<%= cb.Text %>" /> <%= Html.Encode(cb.Text)%><br /> <% i++; } %></p> <p><input type="submit" value="submit" /></p> Of course something similar could be done with Html Helpers, but this works.
I don't know how to solve your problem, but you could define your checkboxes with this code: <%= Html.CheckBox("n[0]") %><%= Html.Hidden("n[0]",false) %> <%= Html.CheckBox("n[1]") %><%= Html.Hidden("n[1]",false) %> <%= Html.CheckBox("n[2]") %><%= Html.Hidden("n[2]",false) %> Hidden fields are needed, because if checkbox is not checked, form doesn't send any value. With hidden field it sends false. Your post method will be: [HttpPost] public ActionResult Test(bool[] n) { return View(); } It may not be optimal and I am open to comments, but it works:) EDIT Extended version: <%= Html.CheckBox("n[0].Checked") %><%= Html.Hidden("n[0].Value",32) %><%= Html.Hidden("n[0].Checked",false) %> <%= Html.CheckBox("n[1].Checked") %><%= Html.Hidden("n[1].Value",55) %><%= Html.Hidden("n[1].Checked",false) %> <%= Html.CheckBox("n[2].Checked") %><%= Html.Hidden("n[2].Value",76) %><%= Html.Hidden("n[2].Checked",false) %> Your post method will be: [HttpPost] public ActionResult Test(CheckedValue[] n) { return View(); } public class CheckedValue { public bool Checked { get; set; } public bool Value { get; set; } } I wrote it without VS, so it may need little correction.
Behold the final solution: public static class Helpers { public static string CheckboxGroup<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> propertySelector, int value) where TProperty: IEnumerable<int> { var groupName = GetPropertyName(propertySelector); var modelValues = propertySelector.Compile().Invoke(htmlHelper.ViewData.Model); var svalue = value.ToString(); var builder = new TagBuilder("input"); builder.GenerateId(groupName); builder.Attributes.Add("type", "checkbox"); builder.Attributes.Add("name", groupName); builder.Attributes.Add("value", svalue); var contextValues = HttpContext.Current.Request.Form.GetValues(groupName); if ((contextValues != null && contextValues.Contains(svalue)) || (modelValues != null && modelValues.Contains(value))) { builder.Attributes.Add("checked", null); } return builder.ToString(TagRenderMode.Normal); } private static string GetPropertyName<T, TProperty>(Expression<Func<T, TProperty>> propertySelector) { var body = propertySelector.Body.ToString(); var firstIndex = body.IndexOf('.') + 1; return body.Substring(firstIndex); } } And in your view: <%= Html.CheckboxGroup(model => model.DocumentCoverCustom, "1")%>(iv),<br /> <%= Html.CheckboxGroup(model => model.DocumentCoverCustom, "2")%>(vi),<br /> <%= Html.CheckboxGroup(model => model.DocumentCoverCustom, "3")%>(vii),<br /> <%= Html.CheckboxGroup(model => model.DocumentCoverCustom, "4")%>(ix)<br />
Well... the check boxes aren't going to know their state on their own, especially if you are not using the Html.CheckBox helper (if you are, see LuKLed's answer). You're going to have to put the checked state of each box in your ViewData (or Model) and then perform a look-up in your View in one way or another. Warning: Really ugly proof-of-concept code: Controller: //validation fails ViewData["checkboxn"] = n; return View(); View: <% int[] n = (int[])ViewData["checkboxn"]; %> <input type="checkbox" name="n" value=1 <%= n != null && n.Contains(1) ? "checked=\"checked\"" : "" %> /> <input type="checkbox" name="n" value=2 <%= n != null && n.Contains(2) ? "checked=\"checked\"" : "" %> /> <input type="checkbox" name="n" value=3 <%= n != null && n.Contains(3) ? "checked=\"checked\"" : "" %> /> All I'm doing here is passing the array n back to the view, and if it contains a value for the respective checkbox, adding checked="checked" to the element. You would probably want to refactor this into an HtmlHelper of your own, or otherwise make this less ugly, of course.
This solution may be of interest to those wanting a clean/simple approach: Maintain state of a dynamic list of checkboxes in ASP.NET MVC I wouldn't really recommend the use of Html.CheckBox unless you have a super simple, single checkbox bound to a single bool (or a couple of static ones at most). When you start having lists of checkboxes in a single array or dynamic checkboxes, it is difficult to work with and you end up programming the whole world in server side bloat just to deal with the shortfalls and get everything working. Forget it, and just use the clean HTML focused solution above and you're up and running quickly with less mess to maintain in the future.
I know this must be insanely late but just incase anyone else finds themselves here.. MVC does have a way to handle checkbox groups. in your view model: [Display(Name = "Which Credit Cards are Accepted:")] public string[] EmployeeRoles{ get; set; } On your Page: <input id="EmployeeRoles" name="EmployeeRoles" type="checkbox" value="Supervisor" #(Model.EmployeeRoles != null && Model.EmployeeRoles.Contains("Supervisor") ? "checked=true" : string.Empty)/> <span>Supervisor</span><br /> <input id="EmployeeRoles" name="EmployeeRoles" type="checkbox" value="Auditor" #(Model.EmployeeRoles != null && Model.EmployeeRoles.Contains("Auditor") ? "checked=true" : string.Empty)/> <span>Auditor</span><br /> <input id="EmployeeRoles" name="EmployeeRoles" type="checkbox" value="Administrator" #(Model.EmployeeRoles != null && Model.EmployeeRoles.Contains("Administrator") ? "checked=true" : string.Empty) /> <span>Administrator</span> I tried very hard to create these controls with razor but no dice. It keeps creating that hidden field you all have referred to. for your checkbox group you don't need that hidden field, just the code I have added above. You can create an html helper to create this code for you. public static HtmlString CheckboxGroup<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> propertySelector, Type EnumType) { var groupName = GetPropertyName(propertySelector); var modelValues = ModelMetadata.FromLambdaExpression(propertySelector, htmlHelper.ViewData).Model;//propertySelector.Compile().Invoke(htmlHelper.ViewData.Model); StringBuilder literal = new StringBuilder(); foreach (var value in Enum.GetValues(EnumType)) { var svalue = value.ToString(); var builder = new TagBuilder("input"); builder.GenerateId(groupName); builder.Attributes.Add("type", "checkbox"); builder.Attributes.Add("name", groupName); builder.Attributes.Add("value", svalue); var contextValues = HttpContext.Current.Request.Form.GetValues(groupName); if ((contextValues != null && contextValues.Contains(svalue)) || (modelValues != null && modelValues.ToString().Contains(svalue))) { builder.Attributes.Add("checked", null); } literal.Append(String.Format("</br>{1} <span>{0}</span>", svalue.Replace('_', ' '),builder.ToString(TagRenderMode.Normal))); } return (HtmlString)htmlHelper.Raw(literal.ToString()); } private static string GetPropertyName<T, TProperty>(Expression<Func<T, TProperty>> propertySelector) { var body = propertySelector.Body.ToString(); var firstIndex = body.IndexOf('.') + 1; return body.Substring(firstIndex); } on your page use it like so: #Html.CheckboxGroup(m => m.EmployeeRoles, typeof(Enums.EmployeeRoles)) I use an enum but you can use any kind of collection
View does not display updated values when using HTML helpers in asp.net mvc
I have such a problem. I change my models fields in controller but doesn't see the changes. Here are the parts of code : this is view Index.aspx <%Html.BeginForm("Index", "First");%> <p> <%=Html.TextBox("Title") %> </p> <p> <%=Html.TextBox("Price") %> </p> <input type="submit" value="Submit" /> <%Html.EndForm();%> this is controller: FirstController.cs public class FirstController : Controller { [AcceptVerbs(HttpVerbs.Get)] public ViewResult Index() { return View(new MyModel()); } [AcceptVerbs(HttpVerbs.Post)] public ViewResult Index(MyModel k) { k.Title = "Title"; return View(k); } and this is model: MyModel.cs public class MyModel { public String Title { get; set; } public Decimal Price { get; set; } } when I change "Title" text box in controller I don't see changes in view public ViewResult Index(MyModel k) { k.Title = "Title"; return View(k); } text box keep its value before submit. Is there any mistake in my code. This problem doesn't appear when I use html standart input tag instead of Html.TextBox: input type="text" id="Title" name="Title" value="<%=Model.Title %> Thank you in advance.
public ViewResult Index(MyModel k) { ModelState.Clear(); k.Title = "Title"; return View(k); } Have you tried to add ModelState.Clear() as in the above sample? Hope this helps!
I have such a problem, but I think that we both don't understand MVC application lifecycle. Let wait other answers
you should do it like this: <%Html.BeginForm("Index", "First");%> <p> <%=Html.TextBox("Title",Model.Title) %> </p> <p> <%=Html.TextBox("Price",Model.Price) %> </p> <input type="submit" value="Submit" /> <%Html.EndForm();%> The Html.TextBox() have a overwrite version take object value arg to populate the text value!