MVC DropDownList OnChange 更新其他表单字段

MVC DropDownList OnChange to update other form fields

我是 MVC 的新手(我正在摆脱传统 ASP.Net 的阴暗面)并且我知道 SO 更像是一个 "why doesn't this work" 但是,作为 MVC 的新手,我只是想问一些东西是如何实现的——我真的没有任何代码或标记,因为我现在不知道怎么做。

是的,使用一个类似的例子...我有一个表单,其中包含 "Widgets" 列表的下拉列表(感谢 SO,让它工作)...然后还有其他具有 "default" 个值的字段 (Length/Height/Width)。

当表单显示时,会显示下拉菜单,但 L/H/W 的表单字段是 empty/disabled,直到用户从 DDL 中选择一个。

现在,在经典的 ASP.Net 世界中,您将在 "onselectedindexchange" 上执行回发,这将查看所选项目,然后使用来自的值更新 L/H/W 字段"master widget entry" 版本。

由于 MVC 没有 post 返回...这是如何实现的?

在 Asp.Net MVC 中,没有 post控件值更改时在 Web 表单中的返回行为。您仍然可以 post 表单,在操作方法中,您可以读取所选值(posted 值)并加载文本框的值并再次呈现页面。这是完整的形式 posting。但是有更好的方法可以使用 ajax 来做到这一点,这样用户就不会体验到整个页面的重新加载。

您要做的是,当用户更改下拉列表时,获取所选项目的值并调用您的服务器以获取您想要在输入字段中显示的数据并进行设置。

为您的页面创建视图模型。

public class CreateViewModel
{
    public int Width { set; get; }
    public int Height{ set; get; }

    public List<SelectListItem> Widgets{ set; get; }

    public int? SelectedWidget { set; get; }    
}

现在在 GET 操作中,我们将为此创建一个对象,初始化小部件 属性 并发送到视图

public ActionResult Create()
{
  var vm=new CreateViewModel();
  //Hard coded for demo. You may replace with data form db.
  vm.Widgets = new List<SelectListItem>
            {
                new SelectListItem {Value = "1", Text = "Weather"},
                new SelectListItem {Value = "2", Text = "Messages"}
            };
 return View(vm);
}

以及您创建的强类型视图 CreateViewModel

@model ReplaceWithYourNamespaceHere.CreateViewModel
@using(Html.BeginForm())
{
    @Html.DropDownListFor(s => s.SelectedWidget, Model.Widgets, "Select");

    <div id = "editablePane" >
         @Html.TextBoxFor(s =>s. Width,new { @class ="myEditable", disabled="disabled"})
         @Html.TextBoxFor(s =>s. Height,new { @class ="myEditable", disabled="disabled"})
    </div>
}

以上代码将为 SELECT 元素呈现 html 标记,并为宽度和高度呈现 2 个输入文本字段。 (在页面上做一个 "view source" 看看)

现在我们将有一些 jQuery 代码侦听 SELECT 元素的 change 事件并读取所选项目的值,进行 ajax 调用服务器获取所选小部件的高度和宽度。

<script type="text/javascript">
 $(function(){

      $("#SelectedWidget").change(function() {

            var t = $(this).val();

            if (t !== "") {               
                $.post("@Url.Action("GetDefault", "Home")?val=" + t, function(res) {
                    if (res.Success === "true") {

                      //enable the text boxes and set the value

                        $("#Width").prop('disabled', false).val(res.Data.Width);
                        $("#Height").prop('disabled', false).val(res.Data.Height);

                    } else {
                        alert("Error getting data!");
                    }
                });
            } else {
                //Let's clear the values and disable :)
                $("input.editableItems").val('').prop('disabled', true);
            }

        });
 });

</script>

我们需要确保在 HomeController 中有一个名为 GetDetault 的操作方法来处理 ajax 调用。

[HttpPost]
public ActionResult GetDefault(int? val)
{
    if (val != null)
    {
        //Values are hard coded for demo. you may replae with values 
       // coming from your db/service based on the passed in value ( val.Value)

        return Json(new { Success="true",Data = new { Width = 234, Height = 345}});
    }
    return Json(new { Success = "false" });
}
  1. 创建控制器“Action”,return“Json”数据。
  2. 使 Ajax 调用下拉列表的“onchange”到那个“Action”。
  3. On ajax "response" (json) 您将获得值然后将这些值设置为 来自 json 响应的字段。

这是更新字段值的方法。