如何绑定MVC Web API中的下拉列表?

时间:2014-07-08 19:18:10

标签: c# asp.net-mvc razor asp.net-web-api

我正在尝试从webapi控制器绑定剃刀视图中的下拉值。但是,为什么它不接受我的webapi中的视图。 view()是否只接受控制器而不是apicontroller?我在View(模型)中收到错误,说"方法,委托或事件是预期的"。

基本上,我试图改变逻辑。早些时候,我向web api发送ajax请求以获取下拉值。现在,我不想使用它。我觉得发送ajax请求不是加载下拉值的更好方法。现在,我想删除ajax调用逻辑并从razor下拉(选择)控件中的web abi控制器加载下拉值。

CS HTML:

 <select id="sltCustomers" name="sltCustomers"></select>

JQuery的:

$(document).ready(function () {
            var planCodes = $('#sltCustomers');

            $.ajax({
                url: '/api/ClearCache/Customers',
                type: "Get",
                success: function(data) {
                    for (var i = 0; i < data.length; i++) {
                        var option = $("<option/>");
                        option.attr("value", data[i]).text(data[i]);
                        planCodes.append(option);
                    }
                },
                error: function(msg) { alert(msg); }
            });

型号:

public IEnumerable<String> GetAllCustomers()
    {
        var customerEntities = new CustomerEntities();
        return customerEntities.Customers.Select(c => c.CustomerName);
    }

Web Api控制器方法:

     //GET api/ClearCache/Customers
    [System.Web.Http.HttpGet]
    public IEnumerable<String> GetCustomers()
    {
        return _clearCache.GetAllCustomers();
    }

现在,我正在尝试将上述逻辑移至控制器。我不想仅为加载值发送ajax请求。

查看型号:

public class CustomerViewModel
{
    [Display(Name = "Name")]
    public IEnumerable<String> Customers { get; set; }
}

Web api方法:

 public ActionResult Customers()
 {
    var model = new CustomerViewModel
    {
        Customers = _clearCache.GetAllCustomers()
    };

    return View(model);
 }

2 个答案:

答案 0 :(得分:3)

Web Api控制器类

public class ValuesController : ApiController
{
    public IEnumerable<string> Get()
    {
        return new string[] { "value1", "value2" };
    }
}

控制器类

public class TestController : Controller
{
    public async Task <ActionResult> Index()
    {
        var model = new CustomerViewModel();

        using (var client = new HttpClient())
        {
            client.BaseAddress = new Uri("http://localhost:54568/");
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

            HttpResponseMessage response = await client.GetAsync("api/Values/");
            if (response.IsSuccessStatusCode)
            {
                var result = await response.Content.ReadAsAsync<IEnumerable<string>>();
                if (result != null)
                    model.Customers = result;
            }
        }

        return View(model);
    }
} 

在视图(.cshtml)中添加以下代码

@model YourNamespace.CustomerViewModel

<select id="sltCustomers" name="sltCustomers">
     @foreach (var item in Model.Customers)
     {
         <option>@item</option>
     }
</select>

我已经测试了代码,它对我来说很好。如果您有任何问题,请告诉我?

不要忘记在WEBAPI类中替换API URL和方法名称。

答案 1 :(得分:0)

这是我的控制器代码

  public async Task<ActionResult> Country()
    {

        var model = new Country();


        using (var client = new HttpClient())
        {
            client.BaseAddress = new Uri("https://localhost:44305/");
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            ViewBag.country = "";
            HttpResponseMessage response = await client.GetAsync("api/v1/doctor/country");
            List<string> li;
            if (response.IsSuccessStatusCode)
            {
                Country co = new Models.Country();
                li = await response.Content.ReadAsAsync<List<string>>();
                ViewBag.country = li;
            }
        }

        return View();
    }

这是我的视图,我将绑定我的下拉列表

<div>

@ Html.DropDownList(&#34; - 选择国家 - &#34;,新的SelectList(ViewBag.Country,&#34; CountryName&#34;))