我正在使用asp.net mvc 4 有没有办法根据用户的选择更新表单?
(在这种情况下,如果从下拉列表中选择某些内容,我想填写地址字段,否则需要输入新地址)
我的模特: 公共类NewCompanyModel {
[Required]
public string CompanyName { get; set; }
public bool IsSameDayRequired { get; set; }
public int AddressID { get; set; }
public Address RegisterOfficeAddress { get; set; }
}
查看:
@model ViewModels.NewCompanyModel
@using (Html.BeginForm(null, null, FormMethod.Post, new { name = "frm", id = "frm" }))
{
@Html.ValidationSummary(true)
<fieldset id="test">
<legend>Company</legend>
<h2>Register office address</h2>
<div class="editor-label">
@Html.LabelFor(model => model.AddressID)
</div>
<div class="editor-field">
@Html.DropDownListFor(model => model.AddressID, (IList<SelectListItem>)ViewBag.Addresses, new {id = "address", onchange = "window.location.href='/wizard/Address?value=' + this.value;" })
</div>
<div class="editor-label">
@Html.LabelFor(model => model.RegisterOfficeAddress.BuildingNameOrNumber)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.RegisterOfficeAddress.BuildingNameOrNumber)
@Html.ValidationMessageFor(model => model.RegisterOfficeAddress.BuildingNameOrNumber)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.RegisterOfficeAddress.StreetName)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.RegisterOfficeAddress.StreetName)
@Html.ValidationMessageFor(model => model.RegisterOfficeAddress.StreetName)
</div>
和控制器:
public ActionResult Address(string value)
{
//get the address from db and somehow update the view
}
问题是如何更新'model.RegisterOfficeAddress.StreetName'等 只是为了说明这只是表格的一部分,所以我还不能提交。
非常感谢
答案 0 :(得分:2)
感谢您的帮助;我决定采取不同的方法: 在下拉列表更改时,我提交表单:
<div class="editor-label">
@Html.LabelFor(model => model.ServiceAddress.AddressID)
</div>
<div class="editor-field">
@Html.DropDownListFor(model => model.ServiceAddress.AddressID, (IEnumerable<SelectListItem>)ViewBag.Addresses, new { onchange = "this.form.submit();" })
@Html.ValidationMessageFor(model => model.ServiceAddress.AddressID)
</div>
然后在控制器中:
[HttpPost]
public ActionResult NewDirector(NewDirectorVM vm, string value)
{
ModelState.Clear();
if (vm.ServiceAddress.AddressID > 0)
{
//Updates the properties of the viewModel
vm.ServiceAddress = _Repository.GetAddress(vm.ServiceAddress.AddressID);
}
return View("NewDirector", vm);
}
请注意ModelState.Clear();
实际上允许从控制器更新视图(否则控制器对viewModel所做的所有更改都会被视图中的值覆盖)。
答案 1 :(得分:1)
在这种情况下,常见的方法是通过javascript更新其他字段:
$('#@Html.IdFor(model => model.AddressID)').on('change',function(){
$.get(...,function(data){
$('#@Html.IdFor(model => model.RegisterOfficeAddress.BuildingNameOrNumber)').val(data)
})
})