简体   繁体   English

Asp.net MVC用JQuery填充一个列表框?

[英]Asp.net MVC populate a list box with JQuery?

I have a list of Payees in a drop down box on my form. 我在表格的下拉框中有一个Payees列表。 I would like to populate a different drop down, based on the selected item of the Payee drop down, without post backs and all that. 我想根据收款人下拉列表中的所选项目填充不同的下拉列表,而不是回发和所有这些。

So, I created a method in my controller that does the work: 所以,我在我的控制器中创建了一个方法来完成工作:

        private JsonResult GetCategories(int payeeId)
    {
        List<CategoryDto> cats = Services.CategoryServices.GetCategoriesByPayeeId(payeeId);
        List<SelectListItem> items = new List<SelectListItem>();

        foreach(var cat in cats)
        {
            items.Add(new SelectListItem {Text = cat.Description, Value = cat.CategoryId.ToString()});
        }

        return Json(items);

    }

Now, I am unsure what to add to my view to get this to work. 现在,我不确定要添加到我的视图中以使其工作。

At the moment, all I have is this: 目前,我所拥有的只是:

 <% using (Html.BeginForm())
   {%>

   <p>
   <%=Html.DropDownList("SelectedAccountId", Model.Accounts, "Select One..", null) %>
   </p>
   <p>
   <%=Html.DropDownList("SelectedPayeeId", Model.Payees, "Select One...", null) %>
   </p>

                         <input type="submit" value="Save" />
<%
    }%>

they populate fine... so when the user selects the SelectedPayeeId drop down, it should then populate a new (Yet to be created?) drop down which holds categories, based on the SelectedPayeeId. 它们填充得很好......所以当用户选择SelectedPayeeId下拉列表时,它应该根据SelectedPayeeId填充一个新的(尚未创建?)下拉列表,该下拉列表包含类别。

So, I think I need to create a JQuery function (Never done JQuery.. so not even sure where it goes) which monitors the Payee drop down for an onChange event? 所以,我认为我需要创建一个JQuery函数(从未完成JQuery ..所以甚至不确定它去哪里)哪个监视onchange事件的Payee下拉? And then call the method I created above. 然后调用我在上面创建的方法。 Does this sound right, and if so, can you guide me in how to achieve this? 这听起来是对的,如果是的话,你可以指导我如何实现这个目标吗?

Your reasoning so far is totally sound. 到目前为止你的推理完全合情合理。 First you are going to want to include the jquery library in your View / Master. 首先,您将要在View / Master中包含jquery库。 You can download a copy of jquery from http://jquery.com/ . 您可以从http://jquery.com/下载jquery的副本。 Add the file to you project and include a <script src="/path/to/jquery.js"> to the <head> of your document. 将文件添加到项目中,并将<script src="/path/to/jquery.js">到文档的<head>中。 You are going to want to add another dropdown to your View (and probably another property to your model). 您将要在View中添加另一个下拉列表(可能还有另一个属性到您的模型)。 We'll call this 'SelectedCategoryId:' 我们称之为'SelectedCategoryId:'

<%=Html.DropDownList("SelectedCategoryId", null, "Select One...", new { style = "display:none;"}) %>

We've set the style of this Drop Down to not be visible initially because there is nothing to select inside of it. 我们已经将此Drop Down的样式设置为最初不可见,因为它内部没有任何内容可供选择。 We'll show it later after we generate some content for it. 我们稍后会在为它生成一些内容后显示它。 Now, somewhere on your page you will want to include a <script> block that will look something like this: 现在,在页面的某个位置,您需要包含一个如下所示的<script>块:

$(document).ready(function() { $('#SelectedPayeeId').change(function() { 
$.ajax({
  type: 'POST',
  url: urlToYourControllerAction,
  data: { payeeId: $(this).val() },
  success: function(data) { 
     var markup = '';
     for (var x = 0; x < data.length; x++ ) {
        markup += '<option value="' + data[x].Value + '">'+data[x].Text+'</option>';
     }
     $('#SelectedCategoryId').html(markup).show();
  }
}); }); });

This code binds the anonymous function written above to the DOM element with the ID of 'SelectedPayeeId' (in this case your dropdown). 此代码将上面编写的匿名函数绑定到ID为“SelectedPayeeId”的DOM元素(在本例中为您的下拉列表)。 The function performs an AJAX call to the url of your method. 该函数对您方法的url执行AJAX调用。 When it receives the results of the request (your JSON you returned) we iterate over the array and build a string of the html we want to inject into our document. 当它收到请求的结果(你返回的JSON)时,我们遍历数组并构建一个我们想要注入到我们文档中的html字符串。 Finally we insert the html into the 'SelectedCategoryId' element, and change the style of the element so it is visible to the user. 最后,我们将html插入'SelectedCategoryId'元素,并更改元素的样式,以便用户可以看到它。

Note that I haven't run this code, but it should be (almost) what you need. 请注意,我没有运行此代码,但它应该(几乎)你需要的。 jQuery's documentation is available at http://docs.jquery.com/Main_Page and the functions I used above are referenced here: jQuery的文档可以在http://docs.jquery.com/Main_Page上找到,我在上面引用的函数在这里引用:

You'd need to make the GetCategories as a public method as it would correspond to an action handler in your controller. 您需要将GetCategories设置为公共方法,因为它对应于控制器中的操作处理程序。

Your jquery code can look like: 您的jquery代码可能如下所示:

<script type="text/javascript">
    $(function() {
 $('#SelectedPayeeId').change(function() {
          $.get('<%= Url.Action("GetCategories", "YourControllerName") %>',
                    {payeeId: $(this).val()}, 
                    function(data) {
                       populateSelectWith($("#Category"), data);

           });
        });
   //Place populateSelectWith method here
});
</script>
The populateSelectWith can fill your dropdown with data like:

  function  populateSelectWith($select, data) {
    $select.html('');
    $select.append($('<option></option>').val('').html("MYDEFAULT VALUE"));
    for (var index = 0; index < data.length; index++) {
        var option = data[index];
        $select.append($('<option></option>').html(option));
      }
    }

I have not tested this code, but I am hoping it runs okay. 我没有测试过这段代码,但我希望它运行正常。

You can find syntax for the jquery ajax get here Since you are not posting any data to the server, you can might as well decorate your controller action with a [HttpGet] attribute 你可以找到jquery ajax到此处的语法因为你没有将任何数据发布到服务器,你也可以用[HttpGet]属性来装饰你的控制器动作

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM