2015-11-19 29 views
0

我有2個模型。在第一個模型中,「Checkmodel」描述了對象的外觀。 第二個模型「Checkmodels」基於「Checkmodel」創建對象列表。顯示對象列表並返回值以查看

現在我嘗試在我的視圖中顯示它,但我只是不知道該怎麼做。

  1. 模型 「Checkmodel」
namespace WebAppMVCtests.Models 
{ 
    public class CheckModel 
    { 
     public string Name { get; set; } 
     public bool IsChecked { get; set; } 
     public CheckModel(string name, bool ischecked) 
     { 
      this.Name = name; 
      this.IsChecked = ischecked; 
     } 
    } 
} 
  • 模型 「Checkmodels」
  • namespace WebAppMVCtests.Models { 
        public class CheckModels : List<CheckModel> 
        { 
         private List<CheckModel> modellist; 
    
         public CheckModels() 
         { 
          modellist = new List<CheckModel>(); 
         } 
    
         public void Add(string name, bool ischecked) 
         { 
          CheckModel newModel = new CheckModel(name, ischecked); 
          this.Add(newModel); 
         } 
        } 
    } 
    

    控制器

    namespace WebAppMVCtests.Controllers 
    { 
        public class HomeController : Controller 
        { 
         // GET: Home 
         [HttpGet] 
         public ActionResult Index() 
         { 
          CheckModels chmdls = new CheckModels(); 
    
          List<string> e = new List<string>(); 
    
          e.Add("John"); 
          e.Add("Kevin"); 
          e.Add("Mark"); 
    
          string name = ""; 
          bool ischecked = false; 
    
          foreach (var dir in e) 
          { 
           CheckModel newCheckModel = new CheckModel(name, ischecked); 
    
           chmdls.Add(newCheckModel); 
          } 
    return View(); 
         } 
    
         [HttpPost] 
         public ActionResult Index(List<CheckModel> list) 
         { 
          return View(); 
         } 
        } 
    } 
    

    查看

    @model WebAppMVCtests.Models.CheckModels 
    @{ 
        ViewBag.Title = "Index"; 
    } 
    <h2>Index</h2> 
    
    @using (Html.BeginForm()) 
    { 
        for (var i = 0; i < Model.Count(); i++) 
        { 
         <table> 
          <tr> 
           <td> 
            @Html.DisplayFor(it => it[i].Name) 
           </td> 
           <td> 
            @Html.CheckBoxFor(it => it[i].IsChecked) 
           </td> 
          </tr> 
         </table> 
    
        } 
    
        <input id="Submit1" type="submit" value="submit" /> 
    
    } 
    
    +0

    什麼是顯示視圖時,你所面臨的問題? – niksofteng

    +0

    我會添加我的視圖。我試圖用for循環顯示列表,但我總是得到一個NULL異常。 – Drummer

    +0

    調試你的視圖剃鬚刀,看看你在'模型'中得到了什麼? – niksofteng

    回答

    0

    索引中的方法做到這一點:

    return View(chmdls); 
    
    +0

    有用,但不應該顯示名稱? NULL異常消失,知道我看到3個複選框。你也許知道我如何從列表中獲取值?我想在我的控制器中執行如下操作:if(check == true){「insert name into Database」} – Drummer

    +0

    也顯示名稱!我的錯。如果您知道如何將參數傳遞給控制器​​,我仍然感興趣。 – Drummer