Tag Archives: API method Populate as @Html.DropDownList in MVC

[Strongly Type] – Web API method Populate as @Html.DropDownList in MVC project’s Create/Edit view

Base class that can populate list

using System.Web.Mvc;

namespace LibraryApp.Core.Entities
{
    public class Book
    {
        ...

        public IEnumerable<SelectListItem> Authers { get; set; }
    }
}

To get the System.Web.Mvc I have to install 'System.Web.Mvc.Extensions.Mvc.4'

Basic Class

public class Basic
{
    public int ID { get; set; }        
    public string NAME { get; set; }
}

Get Authers Id and Name Method

Business Logic

public IEnumerable<Basic> GetAuthersIdName()
{
     .....
}

So in Web API layer Controller Class I’m getting above details like below

URL

    // GET: api/Authers/all

    [System.Web.Http.Route("api/Authers/all")] 
    public IEnumerable<Basic> GetAuthersIdName()
    {
        return db.GetAuthersIdName();
    }

Then I can have following URL to fetch above details

http://localhost:13793/api/Authers/all

So In my MVC Layer , model folder I created a class to handle above details like below

public class LibraryClient
{
    private string AUTHER_URL = "http://localhost:13793/api/Authers";

    //DropDown

    public IEnumerable<Basic> GetAuthersIdName()
    {
        try
        {
            HttpClient client = new HttpClient();
            client.BaseAddress = new Uri(AUTHER_URL);
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            HttpResponseMessage response = client.GetAsync("Authers/all").Result;
            if (response.IsSuccessStatusCode)
                return response.Content.ReadAsAsync<IEnumerable<Basic>>().Result;
            return null;
        }
        catch
        {
            return null;
        }

    }
}

Then I create Controller class to populate above details on front end like below

Controller Class

public class BooksController : Controller
{
    // GET: Books/Create
    public ActionResult Create()  
    {
            Book model = new Book
            {
                //Method 1
                Authers = new SelectList(lc.GetAuthersIdName(), "ID", "NAME");
                //Method 2
                Authers = lc.GetAuthersIdName().Select(x => new SelectListItem { Value = x.ID.ToString(), Text = x.NAME })
            };
            return View(model);
    }

    // POST: Books/Create
    [HttpPost]
    public ActionResult Create(Book book)
    {
        LibraryClient lc = new LibraryClient();
        lc.CreateBook(book);
        return RedirectToAction("BookswithAuthers", "BookWithAuther");
    }
}

View File

 @Html.LabelFor(model => model.Auther_Id, "Auther_Id", htmlAttributes: new { @class = "." })

@Html.DropDownListFor(m => m.Auther_Id, Model.Authers, "---Select---", htmlAttributes: new { @class = "form-control" }) @Html.ValidationMessageFor(model => model.Auther_Id, "", new { @class = "." })
</div>
Advertisements