How to send POST only part of a complete model from an ASP.NET MVC razor

I have a view with @model declared as type FullModel;

public class FullModel
{
    public IList<Record> SomeRecords {get;set;}
    public Record NewRecord {get;set;}
}

This view displays SomeRecords and also displays the form for publishing the NewRecord method to the controller, defined as:

public ActionResult CreateNew(Record record)
{
    ...
}

Something like that:

@using (@Html.BeginForm("CreateNew", "RecordController"))
{
    @Html.TextBoxFor(x => x.NewRecord.SomeProp)
    ...
}

But this does not work, because the path starts with root FullModel, so the POST data becomes NewRecord.SomeProp, and the controller expects Recordas root, the path should beSomeProp

What is the usual \ right way to handle this?

+4
source share
4 answers

One approach might be to use TextBoxinstead TextBoxForand define your user name:

@using (@Html.BeginForm("CreateNew", "RecordController")) 
{
    @Html.TextBox("SomeProp", Model.NewRecord.SomeProp)
...
}
0
source

, ASP.NET MVC NewRecord . .

:

  • "" EditorTemplates.
  • - (NewRecord).

    @model NewRecord
    
    @Html.TextBoxFor(x => x.SomeProp)
    
  • EditorFor, ASP.NET MVC , , .

     @Html.EditorFor(x => x.NewRecord)
    
0
0

TryUpdateModel.

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

0
source

Source: https://habr.com/ru/post/1598592/


All Articles