2015-12-15 48 views
0

我正在一個網站,我有一個MultiSelectList類別。每個項目可以屬於多個類別,顯然每個類別可以有多個項目。我讓它在我的視圖的下拉列表中選擇正確的項目。但是,一旦我保存,我不知道如何將選定的項目保存回模型。保存選定的multiSelectList項目回到模型

這裏是我的模型:

public class WebItem 
{ 
    public string ImId { get; set; } 
    public string itemRef { get; set; } 
    public string name { get; set; } 
    public string Image { get; set; } 
    public string NUTS { get; set; } 
    public string description { get; set; } 
    public string ingredients { get; set; } 
    public string allergens { get; set; } 
    public string price { get; set; } 
    public string saleprice { get; set; } 
    public string quantity { get; set; } 
    private const string DEFAULT_USERNAME = "amyb"; 
    private string _username = DEFAULT_USERNAME; 
    public string username { 
     get { return _username; } 
     set { _username = value; } 
    } 
    [Display(Name = "Active?")] 
    public bool active { get; set; } 
    [Display(Name = "Order online?")] 
    public bool orderonline { get; set; } 
    [Display(Name = "Food?")] 
    public bool isfood { get; set; } 
    [Display(Name = "Frozen?")] 
    public bool isfrozen { get; set; } 
    [Display(Name = "Overstock?")] 
    public bool isoverstock { get; set; }  
    public string activedate { get; set; } 
    //public int[] catIDs { get; set; } 
    public List<Category> Categories { get; set; } 
    public IEnumerable<SelectListItem> categories { get; set; } 

    private List<int> selectedCategories; 
    public List<int> SelectedCategories 
    { 
     get 
     { 
      if (selectedCategories == null) 
      { 
       selectedCategories = Categories.Select(m => int.Parse(m.catID)).ToList(); 
      } 
      return selectedCategories; 
     } 
     set { selectedCategories = value; } 
    } 

} 

public class Category 
{ 
    public Category() 
    { 

    } 

    public Category(string catID, string name, string longname) 
    { 
     this.catID = catID; 
     this.name = name; 
     this.longname = longname; 
    } 

    public string catID { get; set; } 
    public string name { get; set; } 
    public string longname { get; set; } 
} 

相關的控制器代碼:

public ActionResult UpdateItem(string ImId) 
    { 
     WebItem item = new WebItem(); 
     List<Category> categories = HomeModel.getAllCategories(); 

     //var selectCategories = categories.Select(c => new 
     //{ 
     // CategoryID = c.catID, 
     // CategoryName = c.longname 
     //}).ToList(); 

     //item.categories = new MultiSelectList(selectCategories, "CategoryID", "CategoryName"); 

     item.categories = categories.Select(c => new SelectListItem 
     { 
      Text = c.name, 
      Value = c.catID 
     }); 

     if (ImId != null && !ImId.Equals("")) 
     { 
      string query = "SELECT 'Image', 'NUTS', ..."; 

      MySqlConnection con; 
      //WebItem item = new WebItem(); 
      try 
      { 
       con = new MySqlConnection(); 
       con.ConnectionString = appConfig._...; 
       con.Open(); 

       item = con.Query<WebItem>(query, new { imid = ImId }).FirstOrDefault(); 
       string activedate = item.activedate; 
       if (activedate.Contains(' ')) 
       { 
        string[] activedates = activedate.Split(' '); 
        item.activedate = activedates[0]; 
       } 
       //List<Category> categories = HomeModel.getAllCategories(); 

       //var selectCategories = categories.Select(c => new 
       //{ 
       // CategoryID = c.catID, 
       // CategoryName = c.longname 
       //}).ToList(); 

       query = "SELECT ..."; 

       try 
       { 
        item.SelectedCategories = con.Query<int>(query, new { pid = ImId }).ToList(); 
       } 
       catch (MySqlException ex) 
       { 

       } 

       //item.categories = new MultiSelectList(selectCategories, "CategoryID", "CategoryName", item.catIDs); 

      } 
      catch (MySqlException ex) 
      { 
       // show error somehow 
       //return View(ex.Message); 
      } 

     } 
     return View(item); 
    } 

    [HttpPost] 
    public ActionResult UpdateItem(WebItem item) 
    { 

     string result = HomeModel.insertUpdateItem(item); 
     TempData["Message"] = item.name + " has been inserted/updated."; 
     return RedirectToAction("WebItems"); 
    } 

而且我的觀點的相關部分:

<div class="form-group"> 
     @Html.LabelFor(model => model.categories, htmlAttributes: new { @class = "control-label col-md-2" }) 
     <div class="col-md-10"> 
      @*@Html.DropDownList("category", (MultiSelectList)Model.categories, new { multiple = "multiple", htmlAttributes = new { @class = "form-control" } })*@ 
      @Html.ListBoxFor(m => m.SelectedCategories, Model.categories) 
      @Html.ValidationMessageFor(model => model.categories, "", new { @class = "text-danger" }) 
     </div> 
    </div> 

我目前沒有任何代碼處理我的[HttpPost]部分中的類別。但我確定我需要那裏的東西。而且我不確定我的模型或視圖是否正確。

+0

還不是很清楚你問什麼,或者什麼具體的你有問題迄今爲止遇到了您的代碼。 –

+0

你的模型需要一個屬性來綁定選定的值,看起來應該是'int [] catIDs',在這種情況下使用'@ Html.ListBoxFor(m => m.catIDs,Model.categories,new {@class = 「form-control」})'(但不知道'categories'和'CategoryChoices'是什麼) –

+0

究竟是什麼「類別」類型?以及該類型如何連接到「WebItem」? – Hadee

回答

1

您可以將數組類型的新屬性添加到您的vie wmodel中,以便從多選框中存儲選定的選項。當表單發佈時,MVC模型綁定將正確綁定選定值到此視圖模型的對象只要我們在我們的HttpPost操作方法中將其作爲參數。

public class CreateWebItem 
{ 
    public string Name{ get; set; } 
    public List<SelectListItem> Categories { set; get; } 
    public int[] SelectedCategories { set; get; } 
    //Add other properties NEEDED FOR THE VIEW 
} 

而在你的GET操作

public ActionResult Create() 
{ 
    var vm = new CreateWebItem(); 
    //Hard coded for demo. you may replace with values from db 
    v.Categories = new List<SelectListItem> 
    { 
    new SelectListItem { Value="1", Text="Dinner" }, 
    new SelectListItem { Value="2", Text="Lunch" }, 
    new SelectListItem { Value="3", Text="Snacks" }, 
    new SelectListItem { Value="4", Text="Drinks" } 
    }; 
    return View(vm); 
} 

並在其中是強類型的CreateWebItem視圖模型的Razor視圖。

@model CreateWebItem 
@using (Html.BeginForm()) 
{ 
    <label>FirstName </label>@Html.TextBoxFor(d => d.Name) 
    <label>Categories</label> 
    @Html.ListBoxFor(s=>s.SelectedCategories,Model.Categories) 
    <input type="submit" value="Add" /> 
} 

而當表單被提交,你可以使用SelectedCategories屬性來獲取編號的數組(所選選項)

[HttpPost] 
public ActionResult Index(CreateWebItem model) 
{ 
    //read model.SelectedCategories array 
    // to do : Save to somewhere and do a redirect (PRG pattern) 
} 
相關問題