gpt4 book ai didi

c# - 根据下拉选择填写表单(MVC 4)

转载 作者:行者123 更新时间:2023-11-30 12:12:10 24 4
gpt4 key购买 nike

我正在使用 asp.net mvc 4有没有一种方法可以根据用户所做的选择来更新表单?

(在这种情况下,如果从下拉列表中选择了某些内容,我想填写地址字段,否则需要输入新地址)

我的模型: 公共(public)类 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>

和 Controller :

 public ActionResult Address(string value)
{
//get the address from db and somehow update the view
}

问题是如何更新“model.RegisterOfficeAddress.StreetName”等澄清一下,这只是表格的一部分,所以我现在还不能提交。

非常感谢

最佳答案

感谢您的帮助;我决定采取不同的方法:在下拉更改时,我提交表单:

<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>

然后在 Controller 中:

  [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(); 它实际上允许从 Controller 更新 View (否则 Controller 对 viewModel 所做的所有更改将被查看)。

关于c# - 根据下拉选择填写表单(MVC 4),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14046224/

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