I am trying to render a ViewModel using Razor and MVC3. For some reason my SelectList (WidgetTypes below) does not render even though the rest all render just fine. Can anyone shed some light as to why not? I do not want to change the View to use @Html.EditorFor(m => m.SystemName) etc. for each field because I use dynamic models for the widgets which will cause the same problem.
My ViewModel:
public class CreateWidgetViewModel
{
[Required]
public string Title { get; set; }
[Required(ErrorMessage = "The System Name is required")]
[Display(Name = "System Name")]
public string SystemName { get; set; }
[Required]
[Display(Name = "Widget Type")]
public string WidgetType { get; set; }
[Required]
[Display(Name = "Widget Types")]
public SelectList WidgetTypes { get; set; }
}
My Controller:
[HttpGet]
public ActionResult Create()
{
var widgetTypes = from wt in _widgetService.WidgetTypes
select new
{
Name = wt.WidgetName,
WidgetType = wt.GetType().AssemblyQualifiedName
};
var viewModel = new CreateWidgetViewModel
{
WidgetTypes = new SelectList(widgetTypes, "WidgetType", "Name")
};
if (Request.IsAjaxRequest())
{
return PartialView(viewModel);
}
return View(viewModel);
}
My View:
@{
ViewBag.CurrentPage = "widgets";
}
<h2>@ViewBag.Title</h2>
@using (Html.BeginForm())
{
@Html.ValidationSummary(true)
<fieldset>
<div>
@Html.EditorFor(model => model)
</div>
</fieldset>
<div>
<input type="submit" value="Save" /> or @Ajax.ActionLink("Back to list", "Index", "Widget",
new AjaxOptions { HttpMethod = "Get", UpdateTargetId = "ajax-replace" })
</div>
}
You need to use the
Html.DropdownListForhelper if you want to generate a drop down list. The fact that you have usedSelectListas type to some of your properties doesn’t mean that the default editor template will render a<select>box. So you will have to write a custom editor template.You may take a look at the following blog post to see how those default templates are implemented.