1

I know similar questions have been asked regarding complex model binding in ASP.NET MVC, but I am having a problem binding because of a lack of a sufficient prefix coming back on the POST and wondered if there were an easy solution.

I have a view Model that looks something like this:

public class ViewModel<Survey, Contact>
{
    public Survey Model { get; set; }
    public Contact Model2 { get; set; }
}

I then have an action method like this that accepts the POSTed

public ActionResult Survey(
    string id, string id2, SurveyViewModel<Survey, Contact> model)
{
    // code goes here...
}

In my form, the first two id's are from the URL route and I then have form code (using @Html.EditorFor(x => x.Model.SurveyName) or similar), generated with names like this:

<input class="text-box single-line" id="Model_Email"
       name="Model.Email" type="text" value="" />

A post works if I change the name from Model.Email to model.Model.Email, but I am trying to avoid having to create a custom model binder.

Is there

  1. A setting I can make in the view to change the name for all fields rendered in a view using the @Html.EditorFor typed view helpers?
  2. Something I can change using the Bind attribute on the action that would allow it to default binding to that object?

The answer may be "build a custom binder", but I just wanted to pose the question before biting that off.

Thanks for the help. Best Regards,

Hal

rsenna
  • 11,775
  • 1
  • 54
  • 60
Hal
  • 1,229
  • 11
  • 26

1 Answers1

2

You can pass custom viewdata with custom HtmlFieldPrefix to view. Every control rendered with helper will have that prefix.

ViewData.TemplateInfo.HtmlFieldPrefix = "prefix here";

Take a look at this: Forcing EditorFor to prefix input items on view with Class Name?

Community
  • 1
  • 1
karaxuna
  • 26,752
  • 13
  • 82
  • 117
  • 1
    I ended up overriding OnActionExecuting and setting setting HtmlFieldPrefix there. As long as I name my posted view model the same thing as the prefix and any actions that accept it, things seem to work great. – Hal Jan 10 '13 at 18:38
  • I meant OnActionExecuted (post execution, not pre) – Hal Jan 10 '13 at 19:07