ASP.NET MVC Html.DropDownList阿贾克斯填充打电话控制器? [英] ASP.NET MVC Html.DropDownList populated by Ajax call to controller?

查看:101
本文介绍了ASP.NET MVC Html.DropDownList阿贾克斯填充打电话控制器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建为重新psented作为一个DropDownList $ P $字段类型的编辑模板。在编辑器模板的定义,我想用电话将DropDownList填充到控制器返回结果JSON上的操作 - ?任何想法如何做到这一点。

例如是这样的:

 <%@控制语言=C#继承=System.Web.Mvc.ViewUserControl< TheFieldType>中%GT;
&所述;%= Html.DropDownList(.....


解决方案

在编辑器模板提供了一个空的下拉菜单:

 <%= Html.DropDownListFor(
    X => x.PropertyToHoldSelectedValue,
    Enumerable.Empty< SelectListItem>()
     - 装载价值 -
    新{ID =富})
%GT;

然后设置一个控制器的动作,将返回的值:

 公共类FooController的:控制器
{
    公众的ActionResult指数()
    {
        返回JSON(新[] {
            新{ID = 1,值=值1},
            新{ID = 2,值=值2},
            新{ID = 3,值=值3},
        },JsonRequestBehavior.AllowGet);
    }
}

和填充,然后使用AJAX的值:

  $(函数(){
    $ .getJSON(/富/索引,功能(结果){
        VAR DDL = $('#富');
        ddl.empty();
        $(结果)。每个(函数(){
            $(使用document.createElement('选项'))
                .attr('值',this.Id)
                的.text(THIS.VALUE)
                .appendTo(DDL);
        });
    });
});

I wanted to create an editor template for a field type that is represented as a dropdownlist. In the definition of the editor template I would like to populate the DropDownList using a call to an action on the controller returning the results as JSON - Any ideas how to do this?

E.g something like:

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<TheFieldType>" %>
<%= Html.DropDownList(.....

解决方案

In the editor template provide an empty dropdown:

<%= Html.DropDownListFor(
    x => x.PropertyToHoldSelectedValue, 
    Enumerable.Empty<SelectListItem>(), 
    "-- Loading Values --",
    new { id = "foo" }) 
%>

Then setup a controller action that will return the values:

public class FooController: Controller
{
    public ActionResult Index()
    {
        return Json(new[] {
            new { Id = 1, Value = "value 1" },
            new { Id = 2, Value = "value 2" },
            new { Id = 3, Value = "value 3" },
        }, JsonRequestBehavior.AllowGet);
    }
}

And then populate the values using AJAX:

$(function() {
    $.getJSON('/foo/index', function(result) {
        var ddl = $('#foo');
        ddl.empty();
        $(result).each(function() {
            $(document.createElement('option'))
                .attr('value', this.Id)
                .text(this.Value)
                .appendTo(ddl);
        });
    });
});

这篇关于ASP.NET MVC Html.DropDownList阿贾克斯填充打电话控制器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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