MVC DropDownList OnChange更新其他表单字段 [英] MVC DropDownList OnChange to update other form fields

查看:80
本文介绍了MVC DropDownList OnChange更新其他表单字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是MVC的新手(我从传统ASP.Net的阴暗面转移过来),并且我知道SO更像是为什么行不通",但是,对于MVC来说,我只是想询问如何实现某些目标-我实际上没有任何代码或标记,因为我目前不知道该怎么做.

I am new to MVC (I am moving over from the dark side of traditional ASP.Net) and I know that SO is more of a "why doesn't this work" but, being new to MVC, I just wanted to ask how something is achieved - I don't really have any code or markup because I don't know how at the moment.

对,使用类似的示例...我有一个表单,其中包含小部件"列表的下拉列表(感谢SO,它可以正常工作)...然后还有其他字段(Length/高度/宽度)具有默认"值.

Right, using an analogous example... I have a form that has a drop-down of a list of "Widgets" (have that working, thanks to SO) ... and then there are other fields (Length/Height/Width) which have "default" values.

显示表单时,显示下拉菜单,但L/H/W的表单字段为空/禁用,直到用户从DDL中选择一个为止.

When the form displays, the Drop-Down is shown but the form fields of L/H/W are empty/disabled until the user selects one from the DDL.

现在,在经典的ASP.Net世界中,您将在"onselectedindexchange"上执行回发",它将查看选定的项目,然后使用主窗口小部件条目"版本中的值更新L/H/W字段

Now, in clasic ASP.Net world, you would do a PostBack on the "onselectedindexchange" and that would look at the item selected, then update the L/H/W fields with values from the "master widget entry" version.

由于MVC没有回发...该如何实现?

As MVC does not have post back... how is this achieved?

推荐答案

在Asp.Net MVC中,当控件值更改时,没有像在Web窗体中那样的回发行为.您仍然可以发布表单,并且在action方法中,您可以读取选定的值(发布的值)并为文本框加载值,然后再次呈现页面.这是完整的表单过帐.但是有更好的方法使用ajax来做到这一点,这样用户就不会体验到整个页面的重新加载.

In Asp.Net MVC, There is no postback behaviour like you had in the web forms when a control value is changed. You can still post the form and in the action method, you may read the selected value(posted value(s)) and load the values for your text boxes and render the page again. This is complete form posting. But there are better ways to do this using ajax so user won't experience the complete page reload.

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

What you do is, When user changes the dropdown, get the selected item value and make a call to your server to get the data you want to show in the input fields and set those.

为您的页面创建一个视图模型.

Create a viewmodel for your page.

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操作中,我们将创建一个对象,初始化Widgets属性并发送到视图

Now in the GET action, We will create an object of this, Initialize the Widgets property and send to the view

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

And your create view which is strongly typed to 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标记,并为Width和Height呈现2个输入文本字段. (在页面上执行查看源代码"并查看)

The above code will render html markup for the SELECT element and 2 input text fields for Width and Height. ( Do a "view source" on the page and see)

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

Now we will have some jQuery code which listens to the change event of the SELECT element and reads the selected item value, Makes an ajax call to server to get the Height and Width for the selected widget.

<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调用.

We need to make sure that we have an action method called GetDetault inside the HomeController to handle the ajax call.

[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" });
}

这篇关于MVC DropDownList OnChange更新其他表单字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆