2011-04-20 49 views
0

我有以下我的申请表:问题与ViewData的在ASP.NET MVC 3

BookCatalogue

--id(PK)

--BookName

--AuthorID( FK)

作者

--id(PK)

--FirstName

--LastName

在编辑视图bookCatalogue我想显示ID,但作者的名单不是文本框。

这是我的代码:

控制器

public ActionResult Edit(int id) 
    { 
     ViewData["Authors"] = _authorRepository.GetAllAuthors(); 
     var book = _bookCtalogueRepository.GetBookById(id); 
     if (book == null) 
      throw new Exception("Book not found"); 
     return View(book); 
    } 

视图(此只显示名字)

... 
     <div> 
      @Html.LabelFor(model => model.Author) 
     </div> 
     <div> 
      @Html.DropDownList("ID", new SelectList(ViewData["Authors"] as System.Collections.IEnumerable, 
     "ID", "LastName" , Model.AuthorID)) 
     </div> 
... 

我有两个问题:

1)如何结合姓和姓氏在一个DropDownList?

2)当我更改LastName和BookName并尝试保存更改时,只有新的BookName发生更改。

这是我的代码用来保存更改

[HttpPost] 
    public ActionResult Edit(int id, FormCollection collection) 
    { 
     var book = _bookCtalogueRepository.GetBookById(id); 
     if (TryUpdateModel(book)) 
     { 
      _bookCtalogueRepository.SaveChanges(); 
      return RedirectToAction("Index"); 
     } 
     else 
     { 
      ViewData["Genres"] = _genreRepository.GetAllGenres(); 
      ViewData["Authors"] = _authorRepository.GetAllAuthors(); 
      return View(book); 
     } 
    } 

谢谢。

+0

你在哪里改变你的姓? – 2011-04-21 03:49:00

回答

0

如何在一个DropDownList中结合FirstName和Lastname?

ViewData["Authors"] = _authorRepository 
    .GetAllAuthors() 
    .Select(a => new { 
     ID = a.ID, 
     FullName = string.Format("{0} {1}", a.FirstName, a.LastName) 
    }); 

然后:

@Html.DropDownList(
    "ID", 
    new SelectList(
     ViewData["Authors"] as System.Collections.IEnumerable, 
     "ID", 
     "FullName", 
     Model.AuthorID 
    ) 
)