【问题标题】:dropdownList insert NULL下拉列表插入 NULL
【发布时间】:2013-03-04 23:29:14
【问题描述】:

我在这里搜索了很多,找到了这样的东西来制作下拉列表

这是我的控制器: 这会将我的数据传递给 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.DropDownList("Id", (SelectList) ViewBag.Id, "--Select One--") 
            </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.CategoryName.Id)
            @Html.ValidationMessageFor(model => model.CategoryName.Id)
        </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_Id 为 NULL 我错过了什么? 和 CategoryName =profits.CategoryName 这是利润中类别的外键 public Categories CategoryName { get; set; }

【问题讨论】:

  • Value = Convert.ToString(c.Id) 可能会解决这个问题
  • 你能添加WebHFM.Models.Profits的类定义吗?

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


【解决方案1】:

在您的 Id 上调用 .ToString()

model.CategoryMenu = db.Categories.Select(c => new SelectListItem {
                                                    Text = c.Name,
                                                    Value = c.Id.ToString(),
                                                   }
                                          );

【讨论】:

  • @user2026573 除了“这不起作用”之外,您能否提供回溯或其他信息?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-12-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多