Alex Burtsev
Alex Burtsev

Reputation: 12668

How to POST only part of full model from ASP .NET MVC razor view

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

Answers (4)

holly_cheng
holly_cheng

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
}

https://msdn.microsoft.com/en-us/library/system.web.mvc.controller.tryupdatemodel%28v=vs.118%29.aspx#M:System.Web.Mvc.Controller.TryUpdateModel%60%601%28%60%600,System.String,System.Web.Mvc.IValueProvider%29

Upvotes: 1

Scottyjones
Scottyjones

Reputation: 36

You could use a BindAttribute on the action parameter to specify the model has a prefix.

Upvotes: 0

Patrick Hofman
Patrick Hofman

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:

  • Under the Views folder, create a folder named 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

dotnetom
dotnetom

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

Related Questions