0

私はここでよく検索し、ドロップダウンリストを作成するために次のようなものを見つけました
。これが私のモデルです:

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_Idこれはデータベースにデータを挿入しますが、NULL何が欠けていますか? CategoryName = profits.CategoryNameこれは Profits のカテゴリへの外部キー ですpublic Categories CategoryName { get; set; }

4

3 に答える 3

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 に割り当てます。

于 2013-03-05T20:34:30.200 に答える
0

Create() アクションreturn View();は、モデルをビュー メソッドのパラメーターに渡さずに戻ります。

于 2013-03-05T20:09:58.103 に答える
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/>
于 2013-03-05T22:04:16.943 に答える