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

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

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()  
    {
        LibraryClient lc = new LibraryClient();
       //Method 1
       ViewBag.listAuthers = new SelectList(lc.GetAuthersIdName(), "ID", "NAME");
       //Method 2
       ViewBag.listAuthers = lc.GetAuthersIdName().Select(x => new SelectListItem { Value = x.ID.ToString(), Text = x.NAME }); 
        return View("Create");
    }

    // 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.DropDownList("Auther_Id", (IEnumerable)ViewBag.listAuthers, "---Select---", htmlAttributes: new { @class = "form-control" }) @Html.ValidationMessageFor(model => model.Auther_Id, "", new { @class = "." }
</div>
Advertisements