gpt4 book ai didi

javascript - Asp.Net MVC Ajax View 模型未更新

转载 作者:行者123 更新时间:2023-12-02 15:00:44 24 4
gpt4 key购买 nike

我有一个困扰我的问题

假设我有一个 View 模型

public class PersonVM 
{
public int? Id { get; set; }

public string Firstname { get; set; }
}

现在我有一个 View ,它有一个输入框,仅捕获Firstname

@model PersonVM

<form id="frmCreatePerson">
@Html.Bootstrap().TextBoxFor(p => p.Firstname).Placeholder("Firstname")

@Html.Bootstrap().Button().Id("btnSubmit").Text("Create").AppendIcon("fa fa-arrow-right")
</form>

@{
if(Model.Id != null)
{
Html.Partial("_Results", Model)
}
}

我对 Controller 进行了 Ajax 调用,以便为 View 模型生成新的 Id

然后我希望显示更新后的 View 模型。

$('#btnSubmit').click(function () {

var data = $("#frmCreatePerson").serialize();

$.ajax({
url: '@Url.Action("CreatePerson", "Person")',
type: "POST",
data: data
})
.done(function (data) {


})
.fail(function () {
alert("Unable to create.");
});
});

Controller

[HttpPost]
public ActionResult CreatePerson(PersonVM model)
{
model.id = 1;

return PartialView("_Results", model);
}

_Results 部分 View 仅包含

@model PersonVM

@Html.DisplayForModel(Model);

由于某种原因, View 模型未更新并且模型仍然为空。如何向 Controller 提交 Ajax 调用并将更新的 View 模型返回到 Controller 以进行显示?

这是否可以在不重新加载页面的情况下实现(又称标准操作链接)?

最佳答案

您基本上需要使用返回到 DOM 的响应(部分 View 的渲染标记)。因此,首先在页面中创建一个容器 div。

<div id="items"></div>

并在 ajax 方法的 done 事件中,将响应附加到此 div。

$('#btnSubmit').click(function () {

var data = $("#frmCreatePerson").serialize();

$.ajax({
url: '@Url.Action("CreatePerson", "Person")',
type: "POST",
data: data
})
.done(function (data) {

$("#items").append(data); // append the response to DOM

})
.fail(function () {
alert("Unable to create.");
});
});

关于javascript - Asp.Net MVC Ajax View 模型未更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35446051/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com