I am using .net MVC 2.0 and have set up an edit view that receives a custom ViewModel object. The ViewModel is a class with two properties:
// Properties
public Portfolio Portfolio { get; private set; }
public SelectList slSectors { get; private set; }
In my view there is a form with the purpose of updating the Portfolio Object. The SelectList is passed so I can have a dropdown list for the sectors related to a portfolio. Nothing special here, and exactly as I did it in 1.0.
The problem arises when I use the new TextBoxFor and DropDownListFor helper methods.
I am setting them up like this:
<%= Html.ValidationMessageFor(model => model.Portfolio.SectorID)%>
<%= Html.LabelFor(model => model.Portfolio.SectorID)%>
<%= Html.DropDownListFor(model => model.Portfolio.SectorID, Model.slSectors, new { @class = "selectInput" })%>
<%= Html.ValidationMessageFor(model => model.Portfolio.Title)%>
<%= Html.LabelFor(model => model.Portfolio.Title)%>
<%= Html.TextBoxFor(model => model.Portfolio.Title, new { @class = "textInput" })%>
These are producing the following HTML output (respectively):
<span class="field-validation-valid" id="form0_Portfolio_SectorID_validationMessage"></span>
<label for="Portfolio_SectorID">SectorID</label>
<select class="selectInput" id="Portfolio_SectorID" name="Portfolio.SectorID"><option selected="selected" value="2">Education</option>
Law
<span class="field-validation-valid" id="form0_Portfolio_Title_validationMessage"></span>
<label for="Portfolio_Title">Title</label>
<input class="textInput" id="Portfolio_Title" name="Portfolio.Title" type="text" value="Portfolio Title" />
Please note that the name and id attributes now carry the "Portfolio" prefix. I assume this is because they are being derived from "model.Portfolio.X". This seems to be interfering with my ability to apply Model Binding in the Controller in the Edit ActionResult.
The ActionResult is as follows:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Edit(int id, FormCollection formData)
{
var portfolio = Repository.GetPortfolio(id);
if (portfolio == null)
return RedirectToAction("NotFound");
try
{
UpdateModel(portfolio);
portfolio.DateUpdated = DateTime.Now;
Repository.Save();
return RedirectToAction("Index");
}
catch (Exception e)
{
ModelState.AddModelError("_Form", e.Message);
}
return View(new vmPortfolio(portfolio));
}
How can I either (a) stop the "Portfolio" prefix from being applied in the View, or (b) get ModelBinding working with it present.
Thanks,
Mike