Hal
Hal

Reputation: 1264

ASP.NET MVC Binding to View Model as well as routed values

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

Upvotes: 1

Views: 288

Answers (1)

karaxuna
karaxuna

Reputation: 26930

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?

Upvotes: 2

Related Questions