Proper way to update entity from controller Edit action?

后端 未结 1 364
北荒
北荒 2021-01-24 03:50

Controller

First I tried this:

[HttpPost]
public ActionResult Edit(JournalEntry journalentry)
{
    if (ModelState.IsValid)
    {
               


        
相关标签:
1条回答
  • 2021-01-24 04:11

    Actually you could rename the JournalEntryId property in your JournalEntry view model to Id and then the default model binder will automatically populate it for you so that you don't have to write the following line:

    journalentry.JournalEntryId = id;
    

    and your first code snippet will work because the Id property will be populated with the value from the route.

    Or if for some reason you cannot rename the property on your view model (actually I know the reason => you are not using any view models at all but you are passing your domain entities directly to the view which is bad but subject to another question), you could use a hidden field in your form:

    @Html.HiddenFor(model => model.JournalEntryId)
    

    or modify your Html.BeginForm declaration to include the parameter as query string argument:

    @Html.BeginForm("Edit", "SomeController", new { JournalEntryId = Model.JournalEntryId }, FormMethod.Post)
    {
        ...        
    }
    
    0 讨论(0)
提交回复
热议问题