[英]MVC load partial using ajax and complex object
我有一個主視圖,可加載部分數據視圖。 這是初始加載時使用的代碼:
<div id="customerdetailsDIV" class="well main-well clearfix">
@Html.Partial("_customer_details", Model.customerviewmodel)
</div>
這是局部視圖,以下是示例,但所有數據均已綁定。 該腳本將模型和URL傳遞給我的common.js文件:
@model myproject.Models.customerdetails
<div class="col-md-5ths plain-well">
<label>Title:</label>
@Html.TextBoxFor(x => x.title, new { @class = "form-control" })
</div>
// etc //
<div class="col-md-5ths plain-well">
<div id="customerSaveBtn" class="btn btn-success btn-block">Save</div>
</div>
<script>
var url = "@Url.Action("savecustomerdetails", "Home")";
var model = @Html.Raw(Json.Encode(Model));
</script>
以下是我的common.js中的javascript:
$("#customerSaveBtn").on("click", function () {
$.ajax({
type: "POST",
data: JSON.stringify(model),
url: url,
contentType: "application/json"
}).done(function (res) {
$("#customerdetailsDIV").html(res);
});
});
這回發給我的控制器:
[HttpPost]
public PartialViewResult savecustomerdetails([System.Web.Http.FromBody] customerdetails model)
{
mycontext db = new mycontext();
CustomerDetail item = db.CustomerDetails.Where(x => x.CustomerID == model.customerID).FirstOrDefault();
item.FirstName = model.forename;
// etc //
db.SaveChanges();
return PartialView("_customer_details", model);
}
我的問題是,如果我在控制器中設置了一個斷點,則傳遞的模型不包含視圖中新輸入的數據,而僅包含初始數據,因此綁定似乎不起作用。
第二個問題是,如果我在控制器中手動設置一個文本字段來測試部分文本,則不會使用新數據刷新。
編輯:
我已經根據答案更改了代碼
<div id="customerdetailsDIV" class="well main-well clearfix">
@using(Html.BeginForm()) {
@Html.Partial("_customer_details", Model.customerviewmodel)
}
</div>
$("#customerSaveBtn").on("click", function () {
$.ajax({
type: "POST",
data: $("#customerdetailsDIV > form").serialize(),
url: url,
contentType: "application/json"
}).done(function (res) {
$("#customerdetailsDIV").html(res);
});
});
我的突破點根本沒有被擊中。 是因為我的控制器正在期待我的模型嗎?
只需在View中創建表單,然后將帶有部分幫助器的div放入其中
@using(Html.BeginForm()) {
<div id="customerdetailsDIV" class="well main-well clearfix">
@Html.Partial("_customer_details", Model.customerviewmodel)
</div>
}
然后序列化此表單並使用ajax發布。
$("#customerSaveBtn").on("click", function () {
$.ajax({
type: "POST",
data: $("#customerdetailsDIV").closest("form").serialize(),
url: url,
contentType: "application/json"
}).done(function (res) {
$("#customerdetailsDIV").html(res);
});
});
在努力使表格生效之后,我最終經歷了@ramiramilu建議的回合
$("#customerSaveBtn").on("click", function () {
var model = {
customerID: $('#customerID').val(),
title: $('#title').val(),
forename: $('#forename').val(),
surname: $('#surname').val(),
address1: $('#address1').val(),
address2: $('#address2').val(),
address3: $('#address3').val(),
address4: $('#address4').val(),
postcode: $('#postcode').val(),
email: $('#email').val(),
contact: $('#contact').val()
};
$.ajax({
type: "POST",
data: JSON.stringify(model),
url: url,
contentType: "application/json"
}).done(function (res) {
$("#customerdetailsDIV").html(res);
});
});
這解決了原始帖子中的兩個問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.