public class HomeModel
{
public PersonModel Person { get; set; }
}
public class PersonModel
{
public string FirstName { get; set; }
public string LastName { get; set; }
public AddressModel Address { get; set; }
}
public class AddressModel
{
public string AddressLine1 { get; set; }
public string AddressLine2 { get; set; }
}
public class HomeController : Controller
{
public ActionResult Index()
{
HomeModel model = BuildHomeModel();
return View(model);
}
[HttpPost]
public ActionResult Save(HomeModel model)
{
if (model.Person.Address == null)
{
return Json("address cannot be null");
}
return Json("success");
}
[HttpGet]
public ActionResult GetAddress()
{
AddressModel address = GetNewAddress();
return PartialView("~/Views/Shared/EditorTemplates/_Address.cshtml", address);
}
}
Index.cshtml
@model Models.HomeModel
<form id="mainForm">
@Html.EditorFor(x => x.Person, "_Person")
</form>
<button class="btn btn-default" id="btnSave">Save</button>
<button class="btn btn-default" id="refreshAddress">Refresh Address</button>
<script src="~/Scripts/home.js"></script>
_Person.cshtml
@model Models.PersonModel
@Html.LabelFor(x => x.FirstName)
@Html.TextBoxFor(x => x.FirstName)
@Html.LabelFor(x => x.LastName)
@Html.TextBoxFor(x => x.LastName)
<div id="PersonAddress">
@Html.EditorFor(x => x.Address, "_Address")
</div>
_Address.cshtml
@model Models.AddressModel
@Html.LabelFor(x => x.AddressLine1)
@Html.TextBoxFor(x => x.AddressLine1)
@Html.LabelFor(x => x.AddressLine2)
@Html.TextBoxFor(x => x.AddressLine2)
JavaScript
$(function () {
$("#btnSave").click(function () {
$.ajax({
type: "POST",
url: "/home/save",
data: $("#mainForm").serialize(),
contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
processData: true,
cache: false
})
.done(function (response, textStatus, jqXHR) {
alert(response);
})
})
$("#refreshAddress").click(function () {
$("#PersonAddress").load("/home/getaddress");
})
})
当视图加载地址相关的输入元素时,具有正确的名称和id。
<input name="Person.Address.AddressLine1" id="Person_Address_AddressLine1" type="text" >
<input name="Person.Address.AddressLine2" id="Person_Address_AddressLine2" type="text" >
当我点击Refresh Address
按钮,服务器将以_Address
具有新地址的部分视图,在jQuery中,我替换PersonAddressdiv
。但是现在输入元素的名称和id是不同的
<input name="AddressLine1" id="AddressLine1" type="text" value="4200 Park">
<input name="AddressLine2" id="AddressLine2" type="text" value="New York, NY 12345">
我正在寻找任何其他解决方案,如果有任何(最好是服务器端)?
发布于 2018-08-02 09:52:53
你可以设置HtmlFieldPrefix
在控制器方法中。
首先,EditorTemplate
应该与类命名相同,即AddressModel.cshtml
,并位于/Views/Shared/EditorTemplates
(或/Views/YourControllerName/EditorTemplates
)文件夹,然后在视图中它只是
@Html.EditorFor(x => x.Address)
然后在get方法中返回部分
[HttpGet]
public ActionResult GetAddress()
{
AddressModel address = GetNewAddress();
ViewData.TemplateInfo.HtmlFieldPrefix = "Person.Address"; // Add this
return PartialView("AddressModel", address);
}
https://stackoverflow.com/questions/-100001850
复制相似问题