ASP.NET MVC3:控制器中 Null 中 DropdownList 中的对象

发布于 01-07 00:29 字数 4732 浏览 5 评论 0原文

我为 BookShop 创建了一个示例 MVC3 应用程序。我有一个创建操作。在创建操作中,用户输入书名、作者姓名并选择流派名称。它工作正常,没有错误。但在控制器中,我没有获得所选的流派名称(-流派对象为空)。我们该如何纠正呢?

注意:当我编写@Html.DropDownList("GenreId", String.Empty)时,ASP.NET MVC 中内置的模型绑定功能将尝试填充以下对象:使用表单输入的类型。例如,它将尝试设置图书对象的 GenreId 值。但 Book 不包含属性 GenreId。但是,下拉列表可以通过从 ViewBag 读取所需值来显示值。

代码

@model MyBookShopApp.Book

@{
ViewBag.Title = "Create";
}

<h2>Create</h2>

@using (Html.BeginForm()) {

@Html.ValidationSummary(true)

<fieldset>

    <legend>BOOK</legend>


    <div >
        @Html.LabelFor(model => model.Title) :~: @Html.EditorFor(model => model.Title)
    </div>


    <div >
        @Html.LabelFor(model => model.Artist.Name )  :*: @Html.EditorFor(model => model.Artist.Name)
    </div>


    <div >
        @Html.LabelFor(model => model.GenreEntity.Name, "The Genre") ::   @Html.DropDownList("GenreId", String.Empty)
    </div>


    <p>
        <input type="submit" value="Create" />
    </p>

</fieldset>
}

<div>
 @Html.ActionLink("Back to List", "Index")
</div>

控制器

namespace MyBookShopApp.Controllers
{
public class StoreManagerController : Controller
{

    List<GenreEntity> listOfGenres = new List<GenreEntity>()
                                    {
                                       new GenreEntity { Name = "Fiction", GenreId = 1 },
                                       new GenreEntity { Name = "Science", GenreId = 2 },
                                       new GenreEntity { Name = "Religious", GenreId = 3 },
                                    };

    List<Book> bookList = new List<Book>()
                          {
                            new Book
                            {
                                BookId = 1,Title = "Book1",
                                GenreEntity = new GenreEntity { Name = "Fiction", GenreId = 1 },
                                Artist = new Artist { ArtistId = 1, Name = "Dinesh" }
                            },
                            new Book
                            {
                                BookId = 2,Title = "Book2",
                                GenreEntity = new GenreEntity { Name = "Science", GenreId = 2 },
                                Artist = new Artist { ArtistId = 1, Name = "Lijo" }
                            },
                            new Book
                            {
                                BookId = 3,Title = "Book3",
                                GenreEntity = new GenreEntity { Name = "Religious", GenreId = 3 },
                                Artist = new Artist { ArtistId = 1, Name = "Santhosh" }
                            }

                          };





    #region CREATE



    // GET: 
    public ActionResult Create()
    {
                    ViewBag.GenreId = new SelectList(listOfGenres, "GenreId", "Name");
        return View();
    }

    // POST:
    [HttpPost]
    public ActionResult Create(Book theBook)
    {
        if (ModelState.IsValid)
        {
            //Save the book in DB first and then redirectToAction.
            return RedirectToAction("Index");
        }

        return View(theBook);
    }

    #endregion


}
}

图书类

public class Book
{
    public int BookId { get; set; } 
    public string Title { get; set; }
    public GenreEntity GenreEntity { get; set; }
    public Artist Artist { get; set; }

}

GenreEntity

  public class GenreEntity
{
    public string Name { get; set; }
    public int GenreId { get; set; }
}

艺术家类

 public class Artist
{
    public int ArtistId { get; set; }
    public string Name { get; set; }
}

参考

  1. mvc3 中的下拉列表编辑表单

  2. 如何在包含可为空枚举属性的模型的强类型视图中使用 Html.DropDownList?

  3. MVC3 HTML 帮助程序不会在提交表单时更新 DropdownListFor

  4. 选择更改事件 - Html.DropDownListFor

  5. MVC3 @Html.DropDownListFor 不填充所选项目

I have created a sample MVC3 application for BookShop. I have a create action. In the create action users enter name of a book, author name and select a genre name. It is working without errors. But in the controller, I am not getting the selected genre name ( - the genre object comes as null). How do we correct it?

Note: When I write @Html.DropDownList("GenreId", String.Empty) the Model Binding capabilities built into ASP.NET MVC, will attempt to populate an object of that type using form inputs. E.g. it will try to set the book object’s GenreId value. But Book does not contain the property GenreId. However the dropdown can show the values by reading required values from ViewBag.

CODE

@model MyBookShopApp.Book

@{
ViewBag.Title = "Create";
}

<h2>Create</h2>

@using (Html.BeginForm()) {

@Html.ValidationSummary(true)

<fieldset>

    <legend>BOOK</legend>


    <div >
        @Html.LabelFor(model => model.Title) :~: @Html.EditorFor(model => model.Title)
    </div>


    <div >
        @Html.LabelFor(model => model.Artist.Name )  :*: @Html.EditorFor(model => model.Artist.Name)
    </div>


    <div >
        @Html.LabelFor(model => model.GenreEntity.Name, "The Genre") ::   @Html.DropDownList("GenreId", String.Empty)
    </div>


    <p>
        <input type="submit" value="Create" />
    </p>

</fieldset>
}

<div>
 @Html.ActionLink("Back to List", "Index")
</div>

CONTROLLER

namespace MyBookShopApp.Controllers
{
public class StoreManagerController : Controller
{

    List<GenreEntity> listOfGenres = new List<GenreEntity>()
                                    {
                                       new GenreEntity { Name = "Fiction", GenreId = 1 },
                                       new GenreEntity { Name = "Science", GenreId = 2 },
                                       new GenreEntity { Name = "Religious", GenreId = 3 },
                                    };

    List<Book> bookList = new List<Book>()
                          {
                            new Book
                            {
                                BookId = 1,Title = "Book1",
                                GenreEntity = new GenreEntity { Name = "Fiction", GenreId = 1 },
                                Artist = new Artist { ArtistId = 1, Name = "Dinesh" }
                            },
                            new Book
                            {
                                BookId = 2,Title = "Book2",
                                GenreEntity = new GenreEntity { Name = "Science", GenreId = 2 },
                                Artist = new Artist { ArtistId = 1, Name = "Lijo" }
                            },
                            new Book
                            {
                                BookId = 3,Title = "Book3",
                                GenreEntity = new GenreEntity { Name = "Religious", GenreId = 3 },
                                Artist = new Artist { ArtistId = 1, Name = "Santhosh" }
                            }

                          };





    #region CREATE



    // GET: 
    public ActionResult Create()
    {
                    ViewBag.GenreId = new SelectList(listOfGenres, "GenreId", "Name");
        return View();
    }

    // POST:
    [HttpPost]
    public ActionResult Create(Book theBook)
    {
        if (ModelState.IsValid)
        {
            //Save the book in DB first and then redirectToAction.
            return RedirectToAction("Index");
        }

        return View(theBook);
    }

    #endregion


}
}

Book Class

public class Book
{
    public int BookId { get; set; } 
    public string Title { get; set; }
    public GenreEntity GenreEntity { get; set; }
    public Artist Artist { get; set; }

}

GenreEntity

  public class GenreEntity
{
    public string Name { get; set; }
    public int GenreId { get; set; }
}

Artist Class

 public class Artist
{
    public int ArtistId { get; set; }
    public string Name { get; set; }
}

REFERENCE:

  1. dropdown in mvc3 edit form

  2. How to use a Html.DropDownList in a strongly-typed view for a model containing a nullable enum property?

  3. MVC3 HTML helper doesn't update DropdownListFor on Submit the form

  4. on select change event - Html.DropDownListFor

  5. MVC3 @Html.DropDownListFor not populating selected item

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

随梦而飞#2025-01-14 00:29:48

@Html.DropDownList("GenreId", String.Empty) 创建一个名为 GenreId 的 SELECT。然而,MVC3 期望名称 GenreEntity.Name 绑定到 Book。

简单的解决方案是修改 public ActionResult Create(Book theBook)
public ActionResult Create(Book theBook, string GenreId) 来接收发回的 GenreId

或者

@Html.LabelFor(model => model.GenreEntity.GenreId, "The Genre")
@Html.DropDownListFor(model => model.GenreEntity.GenreId, (SelectList)ViewBag.GenreId, String.Empty)

请记住在 HttpPost Create 方法中也设置您的 ViewBag。

编辑
将属性名称从 BookId 更正为 GenreId

@Html.DropDownList("GenreId", String.Empty) creates a SELECT with the name GenreId. However MVC3 is expecting the name GenreEntity.Name to bind to Book.

The simple solution is to modify public ActionResult Create(Book theBook)
to public ActionResult Create(Book theBook, string genreId) to receive the genreId that got posted back

Alternatively

@Html.LabelFor(model => model.GenreEntity.GenreId, "The Genre")
@Html.DropDownListFor(model => model.GenreEntity.GenreId, (SelectList)ViewBag.GenreId, String.Empty)

Remember to set your ViewBag inside the HttpPost Create method also.

Edit
Corrected the property name from BookId to GenreId

时光清浅2025-01-14 00:29:48

您的 DropDown 正在尝试将其值分配给名为 Book.GenreId 的属性。您的 GenreEntity 类具有 GenreId 属性,而不是 Book (基于您上面粘贴的代码)。

您可以通过将下拉列表修改为以下内容来纠正此问题:

@Html.DropDownList("GenreEntity.GenreId", String.Empty)

这将告诉 MVC 将下拉列表的值分配给 Book.GenreEntity.GenreId

Your DropDown is trying to assign its value to a property called Book.GenreId. Your GenreEntity class has the GenreId property, not Book (based on the code you pasted above).

You can correct this by modifying the dropdown to this:

@Html.DropDownList("GenreEntity.GenreId", String.Empty)

This will tell MVC to assign the value of the drop down to Book.GenreEntity.GenreId.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文