我需要 SelectListItem 的值为 int。
所以我把它从数据库中提取出来,在这个过程中将它转换为字符串并存储到 listitem 的值。
public class BookAdd
{
public BookAdd()
{
public Book Book { get; set; }
DataModelContainer db = new DataModelContainer();
IEnumerable<SelectListItem> items = db.PublisherSet
.Select(i => new SelectListItem
{
Value = SqlFunctions.StringConvert((double)i.Id),
Text = i.Name
});
}
}
然后,当从下拉列表中选择时,我需要再次将该值作为 int 存储到 Book.PublisherId。我知道下面的代码不完整,我想我需要以某种方式将所选项目的值转换为 int,我该怎么做?
@model Bookshops.Models.BookAdd
...
@Html.DropDownListFor(model => model.Book.PublisherId, Model.items);
最后是控制器:
public ActionResult Create2()
{
var bookAdd = new BookAdd();
ViewBag.Publisher = bookAdd.items;
return View(bookAdd);
}
//
// POST: /Book/Create
[HttpPost]
public ActionResult Create2(BookAdd book)
{
if (ModelState.IsValid)
{
Book book2 = new Book();
book2.Id = book.Book.Id;
book2.AuthorId = book.Book.AuthorId;
book2.Isbn = book.Book.Isbn;
book2.Id = int.Parse(book.Book.PubId);
book2.Title = book.Book.Title;
book2.YearPublished = book.Book.YearPublished;
db.BookSet.Add(book2);
db.SaveChanges();
}
return RedirectToAction("Index");
}
我正在使用 MVC 3、EF 4。