Reputation: 12668
I have a View with @model declared as FullModel type;
public class FullModel
{
public IList<Record> SomeRecords {get;set;}
public Record NewRecord {get;set;}
}
This view, renders SomeRecords, and also renders Form for posting NewRecord to controller method defined as:
public ActionResult CreateNew(Record record)
{
...
}
Something like this:
@using (@Html.BeginForm("CreateNew", "RecordController"))
{
@Html.TextBoxFor(x => x.NewRecord.SomeProp)
...
}
But this doesn't work, because the path starts from root FullModel
, so the POST data becomes NewRecord.SomeProp
and controller expects Record
as root, the path should be SomeProp
What's the usual \ proper way to deal with this?
Upvotes: 6
Views: 1226
Reputation: 2471
You can also use the TryUpdateModel
method.
public ActionResult CreateNew(FormCollection collection)
{
Record record = new Record();
TryUpdateModel<Record>(record, "NewRecord", collection);
// do more stuff
}
Upvotes: 1
Reputation: 36
You could use a BindAttribute
on the action parameter to specify the model has a prefix.
Upvotes: 0
Reputation: 156998
According to this blog post you should use an Editor Template, which ASP.NET MVC uses to render the editor for NewRecord
in your case. This editor will have the correct naming.
Steps to follow:
EditorTemplates
.Create a view for your sub view model (NewRecord
).
@model NewRecord
@Html.TextBoxFor(x => x.SomeProp)
Use EditorFor
to let ASP.NET MVC render the editor, using the template you've just built.
@Html.EditorFor(x => x.NewRecord)
Upvotes: 0
Reputation: 24901
One approach could be to use TextBox
instead of TextBoxFor
and define your custom name:
@using (@Html.BeginForm("CreateNew", "RecordController"))
{
@Html.TextBox("SomeProp", Model.NewRecord.SomeProp)
...
}
Upvotes: 0