mvc4 dropdownList插入NULL

时间:2013-03-05 20:01:46

标签: c# asp.net-mvc asp.net-mvc-4

我在这里搜索很多并找到这样的东西来制作下拉列表 这是我的模特:

public class Profits
    {
        [Key]
        public int Id { get; set; }
        public double Value { get; set; }
        public string Description{ get; set; }
       [DataType(DataType.Date)]
        public DateTime DateInput { get; set; }
        public UserProfile User { get; set; }
        public Categories CategoryName { get; set; }//foreign key
          public   int CategoryID { get; set; }
    }

 public class Categories
    {
        [Key]
        public int Id { get; set; }
        [Required]
        public string  Name { get; set; }
        public UserProfile User { get; set; }


    }

这是我的控制器: 这传递了我的dropDownList ...

数据
public ActionResult Create()
{
    var dba = new WHFMDBContext();
    var query = dba.Categories.Select(c => new { c.Id, c.Name });
    ViewBag.Id = new SelectList(query.AsEnumerable(), "Id", "Name", 3);
    return View();
}

[HttpPost]
        [InitializeSimpleMembership]
        public ActionResult Create(Profits profits)
        {
            var user = db.UserProfiles.FirstOrDefault(x => x.UserId == WebSecurity.CurrentUserId);
            var profit = new Profits
            {
               Value= profits.Value,
               Description = profits.Description,
               DateInput =profits.DateInput,
               CategoryName =profits.CategoryName,// ???
                User = user,

            };
            db.Profits.Add(profit);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

我的观点:

@model WebHFM.Models.Profits



@using (Html.BeginForm()) {
    @Html.ValidationSummary(true)

    <fieldset>
        <legend>Profits</legend>


    <div class="editor-field">
     @Html.LabelFor(model => model.CategoryName)
        </div>
    <div class="editor-field">
         @Html.DropDownList("Id", (SelectList) ViewBag.Id, "--Select One--") 
        @Html.ValidationMessageFor(model => model.CategoryName)
    </div>

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

这是向数据库插入数据但是CategoryName_IdNULL我错过了什么? 和CategoryName = profits.CategoryName这是利润中的类别public Categories CategoryName { get; set; }

的外键

3 个答案:

答案 0 :(得分:1)

修改您的利润类,添加:

Profits
{
  int CategoryID {get;set;}
}

修改你的cshtml。变化

@Html.DropDownList("Id", (SelectList) ViewBag.Id, "--Select One--") 

@Html.DropDownList("CategoryID", (SelectList) ViewBag.Id, "--Select One--") 

改变你的控制器:

public ActionResult Create(Profits profits)
        {
            var user = db.UserProfiles.FirstOrDefault(x => x.UserId == WebSecurity.CurrentUserId);
            var category = db.Categories.FirstOrDefault(o => o.CategoryId == profits.CategoryID);
            var profit = new Profits
            {
               Value= profits.Value,
               Description = profits.Description,
               DateInput =profits.DateInput,
               CategoryName = category,
               User = user
            };
            db.Profits.Add(profit);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

这样做会更改您的下拉列表以返回所选的CategoryID。标记看起来像:

<select name="CategoryID" />

在您的回发中,这将绑定到您的新Profits.CategoryID。然后使用它来进行数据库查询以获取所选的类别对象,然后将其分配给Profits.CategoryName。

答案 1 :(得分:0)

您的Create()操作返回return View();,而不将模型传递给视图方法参数。

答案 2 :(得分:0)

这是我建议不看你的模型。 PopulateCategoriesDropDownList与创建操作位于同一个控制器中

private void PopulateCategoriesDropDownList(object selectedCategories = null)
    {
        var categoriesQuery = from d in _dataSource.Categories
                         orderby d.Name
                         select d;
        ViewBag.CategoryId= new SelectList(categoriesQuery, "CategoryId", "Name", selectedCategories);
    }

然后您的行为就像这样。

    [HttpGet]
    public ActionResult Create()
    {
      PopulateCategoriesDropDownList();
    return View();
   }


    [HttpPost]
    [InitializeSimpleMembership]
    public ActionResult Create(Profits profits)
    {
         var user = db.UserProfiles.FirstOrDefault(x => x.UserId ==       WebSecurity.CurrentUserId);
        var profit = new Profits
        {
           Value= profits.Value,
           Description = profits.Description,
           DateInput =profits.DateInput,
           CategoryName =profits.CategoryName,// ???
            User = user,

        };
        db.Profits.Add(profit);
        db.SaveChanges();
        PopulateCategoriesDropDownList(profit.CategoryId);
       return View(profit);
    }

在您的视图中

<div class="editor-label">
            @Html.LabelFor(model => model.CategoryId, "Pick Category")
    </div>
    <div class="editor-field">
        @Html.DropDownList("CategoryId", String.Empty)
        @Html.ValidationMessageFor(model => model.CategoryId)
    </div><br/>