2

I am trying to resolve an issue with the following scenario:

  • User loads page and an EditorTemplate ViewModel is loaded.
  • User opens a dialog over the page.
  • This dialog loads the same EditorTemplate ViewModel inside of it.
  • Control IDs are now non-unique due to multiple instances of each control existing in the DOM Tree

My solution for this is to indicate to my controller that I wish to build the ViewModel inside of a Dialog. I do so by indicating a "prefix" string which should be appended onto generated control IDs. I've taken this suggestion from this StackOverflow post.

As such, I have a control declared in my ViewModel as such:

<%--This will append our model's prefix onto all generated IDs to ensure uniqueness.--%>
<% using (Html.BeginHtmlFieldPrefixScope(Model.Prefix)) { %>
<div class="detailsRow required">
    <%= Html.LabelFor(model => model.Name, Model.NameLabel) %>
    <%= Html.EditorFor(model => model.Name) %>
</div>
<% } %>

and in my model:

public NewOrderDetailsModel(string prefix) : this()
{
    Prefix = prefix;
}

This works OK. It has the effect of modifying the control's ID. It renders as 'prefix_Name' not 'Name.'

However, when I post my data to the server -- my changes break MVC's conversion magic:

enter image description here

As you can see, all the properties which had their ID modified come back as null.

Two-part question:

  • Is this the right path to be going down to achieve my desired effect?
  • How can I inform MVC that the IDs have been modified such that I get the JSON-to-Model conversion back?
Community
  • 1
  • 1
Sean Anderson
  • 27,963
  • 30
  • 126
  • 237

1 Answers1

3

The MVC Conversion Magic you speak of is done using the MVC Model Binder. The default model binder will not handle the prefix in this way since it was not made aware of the prefix's existence. You can make it aware by annotating the controller action like so:

public ActionResult SomeAction([Bind(Prefix = "SomePrefix")] ViewModel model){...}

For more information on this, see this post: ASP.NET MVC 3 Model-binding and form fields

Community
  • 1
  • 1
Pat Burke
  • 580
  • 4
  • 13
  • I'm assuming this has to be a constant value, yeah? So I need to separation my Controller's SomeAction's depending on which prefix of ViewModel I expect to pass to the controller? – Sean Anderson Jan 23 '13 at 21:17
  • Yes it will be constant, but this should really be an edge case. If you are going to be running into this situation a lot, consider changing the View Model to be a composite object with all of the information you'll need in one. – Pat Burke Jan 24 '13 at 13:45