Uba
Uba

Reputation: 669

How to bind the dropdownlist in MVC WebAPI?

I am trying to bind dropdown values in razor view from webapi controller. But, why is it not accepting the view in my webapi. whether the view() accepts only in the controller not the apicontroller? I am getting an error in View(model) saying "method, delegate or event is expected".

Basically, I am trying to change the logic. Earlier, I was sending ajax request to web api to get the values for drop down. Now, I don't want to use that. I feel sending an ajax request is not a better approach to load the drop down values. Now, I want to remove ajax call logic and load the drop down values from the web abi controller in razor dropdown (select) control.

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

Model:

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

Web Api controller method:

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

Now, I am trying to move the above logic to controller. I don't want to send ajax request just for loading values.

View Model:

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

Web api method:

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

    return View(model);
 }

Upvotes: 0

Views: 13993

Answers (2)

Debendra Dash
Debendra Dash

Reputation: 5626

Here is my controller Code

  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();
    }

And here is my View where i will bind my Dropdownlist

<div>

@Html.DropDownList("--Select Country--", new SelectList(ViewBag.Country, "CountryName"))

Upvotes: 0

Deepu Madhusoodanan
Deepu Madhusoodanan

Reputation: 1505

Web Api Controller class

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

Controller class

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

Add below code in the View (.cshtml)

@model YourNamespace.CustomerViewModel

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

I have tested the code and it work's fine for me.. let me know if you have any issue?

Don't forget to replace the API URL and the method name in the WEBAPI class.

Upvotes: 3

Related Questions