Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 890
Alex Burtsev Avatar asked Jul 19 '15 14:07

Alex Burtsev


1 Answers

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

like image 107
howcheng Avatar answered Oct 05 '22 10:10

howcheng