【问题标题】:Problem with ViewData in ASP.NET MVC 3ASP.NET MVC 3 中的 ViewData 问题
【发布时间】:2011-04-21 02:10:17
【问题描述】:

我的应用程序中有以下表格:

图书目录

--ID(PK)

--书名

--作者ID(FK)

作者

--ID(PK)

--名字

--姓氏

在 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 中合并 FirstName 和 Lastname?

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);
        }
    }

谢谢。

【问题讨论】:

  • 你在哪里改姓?

标签: asp.net-mvc-3


【解决方案1】:

如何在一个 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
    )
)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-10-02
    • 2012-03-26
    • 2023-03-08
    • 2011-07-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多