ASP.NET MVC3:从DROPDOWNLIST对象在空的控制器 [英] ASP.NET MVC3: Object from DropdownList in Null in Controller

查看:139
本文介绍了ASP.NET MVC3:从DROPDOWNLIST对象在空的控制器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经创建了一个书店MVC3示例应用程序。我有一个创建操作。在创建操作的用户输入一书中,作者姓名的名称,并选择一个流派名称。据工作没有错误。但在控制器,我没有得到所选择的流派名称( - 流派的对象当属无效)。我们如何纠正?

注意::当我写 @ Html.DropDownList(GenreId的String.Empty)内置到ASP.NET模型绑定功能MVC中,将试图填充该型使用形式输入的一个目的。例如。它会尝试设置书对象的GenreId价值。但是本书不包含财产GenreId。但是下拉可以通过ViewBag读取所需值显示的值。

code

  @model MyBookShopApp.Book@ {
ViewBag.Title =创建;
}< H2>创建< / H>@using(Html.BeginForm()){@ Html.ValidationSummary(真)<&字段集GT;    <传奇>书< /传说>
    < D​​IV>
        @ Html.LabelFor(型号=> model.Title):〜:@ Html.EditorFor(型号=> model.Title)
    < / DIV>
    < D​​IV>
        @ Html.LabelFor(型号=> model.Artist.Name):*:@ Html.EditorFor(型号=> model.Artist.Name)
    < / DIV>
    < D​​IV>
        @ Html.LabelFor(型号=> model.GenreEntity.Name,文体):: @ Html.DropDownList(GenreId的String.Empty)
    < / DIV>
    &所述p为H.;
        <输入类型=提交值=创建/>
    &所述; / P>< /字段集>
}< D​​IV>
 @ Html.ActionLink(返回目录,索引)
< / DIV>

控制器

 命名空间MyBookShopApp.Controllers
{
公共类StoreManagerController:控制器
{    清单< GenreEntity> listOfGenres =新的List< GenreEntity>()
                                    {
                                       新GenreEntity {名称=小说,GenreId = 1},
                                       新GenreEntity {名称=科学,GenreId = 2},
                                       新GenreEntity {名称=宗教,GenreId = 3},
                                    };    清单<图书>书目=新的List<图书>()
                          {
                            新书
                            {
                                BOOKID = 1,标题=第一册,
                                GenreEntity =新GenreEntity {名称=小说,GenreId = 1},
                                艺术家=新艺术家{ArtistId = 1,名称=迪内希}
                            },
                            新书
                            {
                                BOOKID = 2,标题=第二册,
                                GenreEntity =新GenreEntity {名称=科学,GenreId = 2},
                                艺术家=新艺术家{ArtistId = 1,名称=Lijo}
                            },
                            新书
                            {
                                BOOKID = 3,标题=BOOK3
                                GenreEntity =新GenreEntity {名称=宗教,GenreId = 3},
                                艺术家=新艺术家{ArtistId = 1,名称=Santhosh}
                            }                          };    #区域CREATE    // GET:
    公众的ActionResult的Create()
    {
                    ViewBag.GenreId =新的SelectList(listOfGenres,GenreId,姓名);
        返回查看();
    }    // POST:
    [HttpPost]
    公众的ActionResult创建(图书theBook)
    {
        如果(ModelState.IsValid)
        {
            //先redirectToAction保存书DB。
            返回RedirectToAction(「指数」);
        }        返回查看(theBook);
    }    #endregion
}
}

图书类

 公共类图书
{
    公众诠释BOOKID {搞定;组; }
    公共字符串名称{搞定;组; }
    公共GenreEntity GenreEntity {搞定;组; }
    公共艺术家艺术家{搞定;组; }}

GenreEntity

 公共类GenreEntity
{
    公共字符串名称{;组; }
    公众诠释GenreId {搞定;组; }
}

艺术家级

 公共类艺术家
{
    公众诠释ArtistId {搞定;组; }
    公共字符串名称{;组; }
}

参考


  1. 在MVC3编辑表格下拉


  2. <一个href=\"http://stackoverflow.com/questions/4904946/how-to-use-a-html-dropdownlist-in-a-strongly-typed-view-for-a-model-containing-a\">How使用Html.DropDownList一个强类型的视图包含一个可空枚举属性模型?


  3. <一个href=\"http://stackoverflow.com/questions/7714490/mvc3-html-helper-doesnt-update-dropdownlistfor-on-submit-the-form\">MVC3 HTML帮助不更新DropdownListFor上提交表单


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


  5. <一个href=\"http://stackoverflow.com/questions/8957000/mvc3-html-dropdownlistfor-not-populating-selected-item\">MVC3 @ Html.DropDownListFor不填充选择项



解决方案

@ Html.DropDownList(GenreId的String.Empty)创建一条SELECT名为GenreId 。然而MVC3期待名称GenreEntity.Name绑定到书。

最简单的解决方法是修改公众的ActionResult创建(图书theBook)
公众的ActionResult创建(图书theBook,串genreId)来接收得到调回了genreId

或者

  @ Html.LabelFor(型号=&GT; model.GenreEntity.GenreId,文体)
@ Html.DropDownListFor(型号=&GT; model.GenreEntity.GenreId,(的SelectList)ViewBag.GenreId,的String.Empty)

记得设置也HttpPost Create方法里面你ViewBag。

修改
来自BOOKID更正的属性名称GenreId

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

解决方案

@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

这篇关于ASP.NET MVC3:从DROPDOWNLIST对象在空的控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆