EF MVC 4 dropdownList中的必需属性失败

时间:2013-04-01 01:08:17

标签: c# asp.net-mvc entity-framework razor asp.net-mvc-4

我用EF创建一个MVC4应用程序,我有两个简单的类,Brand和CarModel,Brand有一个Name(必需),CarModel有一个Brand(必需)。问题是我在ModelState.IsValid上出错了,因为通过下拉菜单选择一个品牌,它只会填写品牌ID。

我如何在品牌名称中保留所需但能够使用CarModel中的下拉列表?这是我的代码:

    public class Brand
    {


        public int Id { get; set; } 
        [Required]       
        public string Name { get; set; }
        public string Logo { get; set; }

    }

    public class CarModel
    {
        public int Id { get; set; }
        [Required]
        public string Name{ get; set; }
        [Required]
        public Brand Brand{ get; set; }
    }

我有完整的Crud for Brand工作正常。但我正在为CarModel做这件事,这就是我在控制器中创建Brand的原因:

 public ActionResult Create()
        {
            ViewBag.BrandSelect = new SelectList(myRepository.GetBrands.ToList(), "Id", "Name");
            return View();
        }

  [HttpPost]
        public ActionResult Crear(CarModel carModel )
        {

            if (ModelState.IsValid)
            {



                myrepository.Create(Modelo);
                return RedirectToAction("Index");
            }


            return View(carModel );
        }

在视图中

<div class="editor-label">
            @Html.LabelFor(model => model.Brand)
        </div>
        <div class="editor-field">

            @Html.DropDownListFor(model => model.Brand.Id,ViewBag.BrandSelect as SelectList)
            @Html.ValidationMessageFor(model => model.Brand)
        </div>

2 个答案:

答案 0 :(得分:2)

如果我理解正确,你的CarModel类应该有BrandId(int)和Brand对象。

public class CarModel
{
    public int Id { get; set; }
    [Required]
    public string Name{ get; set; }
    [Required]
    public int BrandId { get; set; }


    public Brand Brand{ get; set; }
}

您的DropDownList应绑定到BrandId

        @Html.DropDownListFor(model => model.BrandId, ViewBag.BrandSelect as SelectList)
        @Html.ValidationMessageFor(model => model.Brand)

more EF code First Paren-Child

答案 1 :(得分:1)

您在BrandSelect中有预先填充的项目,这意味着Brand.Id保证在数据库中存在。另外,在创建Brand时,您不会创建CarModel。因此,您可以使用代表CarModel的视图模型并将其返回到您的视图,这是最佳做法。考虑一下:

您的模型

public class CarFormModel // this is a "model class" and not your entity
{
    public int Id { get; set; }
    [Required]
    public string Name{ get; set; }
    [Required]
    public int BrandId { get; set; }
    //replacement for your ViewBag.BrandSelect
    //you can also create a viewmodel for this
    //but let's use your entity for a more simple example
    public IEnumerable<Brand> Brands {get;set;}
}

您的控制器,用于GET方法

public ActionResult Create()
{
    var model = new CarFormModel {
        Brands = get_brands_from_database(),
    }
    return View(model);
}

您的观点

@model CarFormModel
<div class="editor-field">
    @Html.TextboxFor(model => model.Name) // capture the name of the car model
<div>
<div class="editor-field">
    @Html.DropDownListFor(model => model.BrandId, new SelectList(Model.Brands,  "Id", "Name", Model.BrandId)) // capture the brand for the car model
    @Html.ValidationMessageFor(model => model.BrandId)
</div>

您的控制器,用于POST方法

[HttpPost]
public ActionResult Create(CarFormModel carModel)
{
    if (ModelState.IsValid) {
        // map the model back to entity or pass it to your service that creates the model
        myrepository.Create(the_mapped_or_created_carmodel_entity);
        return RedirectToAction("Index");
    }

    return View(carModel);
}

此选项优于您现在的选项,因为您没有使用ViewBag作为下拉列表,并且您没有在视图上公开代理对象。一个好的做法是始终在视图上使用视图模型。