使用ajax返回结果更新ViewModel

本文关键字:更新 ViewModel 结果 返回 ajax 使用 | 更新日期: 2023-09-27 18:09:18

我有以下模型

public class PersonViewModel {
    public Guid Id { get; set; }
    public string Firstname{ get; set; }
    public string Lastname { get; set; }
}

我的视图看起来像这样

@model Web.UI.PersonViewModel
<form class="form-horizontal" id="fuelux-wizard" method="post">
    @Html.Bootstrap().TextBoxFor(p => p.Firstname).Placeholder("First name")
    @Html.Bootstrap().TextBoxFor(p => p.Lastname).Placeholder("Last name")
    @Html.Bootstrap().Button().Class("btn btn-next").Text(Model.Id == Guid.Empty ? "Lets Start" : "Continue").HtmlAttributes(new { onclick = "CreatePerson();" }).AppendIcon("fa fa-arrow-right")
</form>

这是当按钮被点击时调用的js函数

function CreateProposal() {
    // DO Ajax call to create the person
    $.ajax({ url: "CreatePerson", type: "POST", data: $('form').serialize() })
      .done(function () {
          $('.wizard').wizard('next');
      })
      .fail(function () {
          alert("Unable to save.");
          $("#personModal").modal("hide");
      });
}

在我的控制器中我也有一个CreatePerson方法

[HttpPost]
public JsonResult CreatePerson(PersonViewModel personViewModel )
{            
    if(personViewModel .Id == Guid.Empty)
        personViewModel .Id = Guid.NewGuid();
     return Json(personViewModel );
}

如何更新视图的ViewModel ?这个想法是创建一个人,这将分配一个新的Guid给模型。当指定了Guid和没有指定Guid时,按钮中的文本会有所不同。

是否有一种方法可以更新视图模型与返回的ajax结果?

谁能给我指个正确的方向吗?

使用ajax返回结果更新ViewModel

听起来你需要这样做:

<form class="form-horizontal" id="fuelux-wizard" method="post">
    @Html.HiddenFor(m => m.Id)
    @Html.Bootstrap().TextBoxFor(p => p.Firstname).Placeholder("First name")
    @Html.Bootstrap().TextBoxFor(p => p.Lastname).Placeholder("Last name")
    @Html.Bootstrap().Button().Class("btn btn-next").Text(Model.Id == Guid.Empty ? "Lets Start" : "Continue").HtmlAttributes(new { onclick = "CreatePerson();" }).AppendIcon("fa fa-arrow-right")
</form>
.done(function (data) {
    $('#Id').val(data.Id);
    $('.wizard').wizard('next');
})

需要在DOM中设置Id。可以将DOM看作是存储来自服务器的数据的数据存储库。