簡體   English   中英

如何在MVC WebAPI中綁定下拉列表?

[英]How to bind the dropdownlist in MVC WebAPI?

我正在嘗試從webapi控制器在razor視圖中綁定下拉值。 但是,為什么它不接受我的webapi中的視圖。 view()是否僅在控制器中接受而不在apicontroller中接受? 我在View(模型)中收到一個錯誤,提示“方法,委托或事件是預期的”。

基本上,我正在嘗試更改邏輯。 之前,我曾向Web api發送ajax請求以獲取下拉列表的值。 現在,我不想使用它。 我覺得發送ajax請求不是加載下拉值的更好方法。 現在,我要刪除ajax調用邏輯,並從razor dropdown(選擇)控件中的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);
 }

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和方法名稱。

這是我的控制器代碼

  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(“-選擇國家-”,新的SelectList(ViewBag.Country,“ CountryName”))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM