如何在 ASP NET MVC 6 中更新模型?

How to Update Model in ASP NET MVC 6?

场景:如何更新模型?

ASPMVC 6

我正在尝试更新模型。为了将模型信息传递给客户端(browser/app),我使用了 DTO。

问题 1:为了更新,我应该 post 返回整个对象吗?

问题2:有什么方法可以方便的只传递更新的信息吗?如果是,如何?

问题3:可以使用JSON补丁进行更新吗?

Question 2: Is there a way I can easily pass only the information that is updated? If yes, how?

是的。您应该创建一个视图模型,它应该只包含视图所需的那些属性。

假设您的用例是构建一个允许用户仅编辑其姓氏的视图。

public class EditUserViewModel
{
  public int Id {set;get;}
  public string LastName {set;get;}
}

并在您的 Get

public ActionResult Edit(int id)
{
  var user = yourUserRepository.GetUser(id);
  if(user!=null)
  {
   var v = new EditUserViewModel { Id=id,LastName=user.LastName};
   return View(v);
  }
  return View("NotFound");
}

和视图

@model EditUserViewModel
@using(Html.BeginForm())
{
  @Html.TextBoxFor(s=>S.LastName)
  @Html.HiddenFor(s=>s.Id)
  <input type="submit" id="saveBtn" />
}

和您的 HttpPost 操作

[HttpPost]
public ActionResult Edit(EditUserViewModel model)
{
   // Since you know you want to update the LastName only, 
   // read model.LastName and use that
   var existingUser = yourUserRepository.GetUser(model.Id);
   existingUser.LastName = model.LastName;
   yourUserRepository.Save();
   // TO DO:  redirect to success page
}

假设 yourUserRepository 是您的数据访问 classes 抽象的对象。

Question 1: For updating, should I post the whole object back?

取决于您希望从最终用户那里得到什么。使用这种视图模型方法,它将 post 只有 Id 和 LastName,这就是我们的用例。

Can I use JSON Patch for updating?

因为你只是发送需要更新的数据(部分数据),你应该没问题。

如果需要,您可以简单地序列化您的表单数据(只有 Id 和 LastName)并使用 jQuery post 方法将其发送到您的服务器。

$(function(){

  $("#saveBtn").click(function(e){

    e.preventDefault(); //prevent default form submit

    var _form=$(this).closest("form");
    $.post(_form.attr("action"),_form.serialize(),function(res){
      //do something with the response.
    });

  });

});

要防止 overposting,您可以在 HttpPost 操作方法上使用 Bind 属性来使用绑定白名单。但最安全的策略是使用与允许客户端发送的内容完全匹配的视图模型class。

而不是这个

UpdateModel(model);

您现在可以调用这个

await TryUpdateModelAsync(model);