0

I have a problem with binding models in mvc 5. For example, I have 2 models:

public class FirstViewModel
{
     public string FirstProperty {get;set;}
     public string SecondProperty {get;set;}
}

and another

public class SecondViewModel
{
     public string SimpleProperty{get;set;}
     public FirstViewModel ComplexProperty {get;set;}
}

I have a strongly typed view with SecondViewModel model class. And in this View I want to have a form for FirstViewModel, witch will be post this to controller. It must be something like this:

View

@model SecondViewModel

@html.EditorFor(x => x.SimpleProperty)
@using(Html.BeginForm("Action", "MyController", FormMethod.Post))
{
   @Html.EditorFor(x => x.FirstViewModel) // I have a custom editor in EditorTemplates folder
<input type="submit" value="submit"/>
}

And controller:

public class MyController : Controller
{
    public ActionResult MyAction(FirstViewModel model)
    {
    }
}

But if I do it in this way the FirstViewModel properties are always empty strings. Thanks for advice

  • try using a partial page instead of EditorFor(). This worked for me. – Martin May 13 '16 at 13:49
  • 1
    you shou include your FirstViewModel inside your view – Feras Salim May 13 '16 at 13:50
  • I assume you mean `@Html.EditorFor(x => x.ComplexProperty)`. You need to use `public ActionResult MyAction([Bind(Prefix = "ComplexProperty")]FirstViewModel model)` to 'strip' the prefix from binding. –  May 14 '16 at 00:37

0 Answers0