Note that there are some explanatory texts on larger screens.

plurals
  1. POUsing ViewModel Pattern with MVC 2 Strongly Typed HTML Helpers
    primarykey
    data
    text
    <p>I am working with ASP.NET MVC2 RC and can't figure out how to get the HTML helper, <strong>TextBoxfor</strong> to work with a <strong>ViewModel pattern</strong>. When used on an edit page the data is not saved when UpdateModel() is called in the controller. I have taken the following code examples from the NerdDinner application.</p> <p>Edit.aspx</p> <pre><code>&lt;%@ Language="C#" Inherits="System.Web.Mvc.ViewUserControl&lt;NerdDinner.Models.DinnerFormViewModel&gt;" %&gt; ... &lt;p&gt; // This works when saving in controller (MVC 1) &lt;label for="Title"&gt;Dinner Title:&lt;/label&gt; &lt;%= Html.TextBox("Title", Model.Dinner.Title) %&gt; &lt;%= Html.ValidationMessage("Title", "*") %&gt; &lt;/p&gt; &lt;p&gt; // This does not work when saving in the controller (MVC 2) &lt;label for="Title"&gt;Dinner Title:&lt;/label&gt; &lt;%= Html.TextBoxFor(model =&gt; model.Dinner.Title) %&gt; &lt;%= Html.ValidationMessageFor(model=&gt; model.Dinner.Title) %&gt; &lt;/p&gt; </code></pre> <p>DinnerController</p> <pre><code>// POST: /Dinners/Edit/5 [HttpPost, Authorize] public ActionResult Edit(int id, FormCollection collection) { Dinner dinner = dinnerRepository.GetDinner(id); if (!dinner.IsHostedBy(User.Identity.Name)) return View("InvalidOwner"); try { UpdateModel(dinner); dinnerRepository.Save(); return RedirectToAction("Details", new { id=dinner.DinnerID }); } catch { ModelState.AddModelErrors(dinner.GetRuleViolations()); return View(new DinnerFormViewModel(dinner)); } } </code></pre> <p>When the original helper style is used (Http.TextBox) the UpdateModel(dinner) call works as expected and the new values are saved. </p> <p>When the new (MVC2) helper style is used (Http.TextBoxFor) the UpdateModel(dinner) call does not update the values. Yes, the current values are loaded into the edit page on load.</p> <p>Is there something else which I need to add to the controller code for it to work? The new helper works fine if I am just using a model and not a ViewModel pattern.</p> <p>Thank you.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload