I have a Controller and I am taking an object of database and passing it to view. Here is the action method for it
public ActionResult NewRequest(Bookinfo bookinfo)
{
using (var db = new Database1Entities1())
{
return View(db.Bookinfoes.ToList());
}
}
And here is my view method
@model IEnumerable<MvcApplication.Models.Bookinfo>
@{
ViewBag.Title = "NewRequest";
}
<h2>NewRequest</h2>
<table>
@foreach (var item in Model)
{
<tr>
<td>
@Html.DisplayFor(modelItem => item.Bookname)
</td>
<td>
@Html.DisplayFor(modelItem => item.Authorname)
</td>
<td>
@Html.DisplayFor(modelItem => item.Publishername)
</td>
<td> </td>
</tr>
}
</table>
As you can see that I am able to display the data normally but i want to display the data in drop downlist. Also I want to select an item from dropdownlist and take its value so that i can manipulate it How can I do it??? Sorry if this seems to be a simple question. i have just started learning asp.net mvc4
Here is the book info model
namespace MvcApplication.Models
{
using System;
using System.Collections.Generic;
public partial class Bookinfo
{
public int Id { get; set; }
public string Bookname { get; set; }
public string Authorname { get; set; }
public string Publishername { get; set; }
}
}
DropDownList
helper will make your drop down list. All you have to do is to build your SelectList
dropdownlist content. You can try this :
// Remove foreach loop
<tr>
<td>
@Html.DropDownList("Bookname", Model.Select(m => new SelectListItem() { Text = m.BookName, Value = m.Bookname} ).ToList())
</td>
<td>
@Html.DropDownList("Authorname", Model.Select(m => new SelectListItem() { Text = m.Authorname, Value = m.Authorname} ).ToList())
</td>
<td>
@Html.DropDownList("Publishername", Model.Select(m => new SelectListItem() { Text = m.Publishername, Value = m.Publishername} ).ToList())
</td>
<td> </td>
</tr>
In controller store the select list into View Bag:
ViewBag.BookinfoId = new SelectList(db.Bookinfoes, "BookinfoId", "BookinfoName");
And in your view Use the ViewBag Name to bind the dropdown :
@Html.DropDownList("BookinfoId", "Select")
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.