显示列表从控制器返回到视图ASP.NET MVC4中的表

时间:2015-02-17 09:04:43

标签: asp.net-mvc asp.net-mvc-4 ienumerable

我的控制器类中有一个函数,它返回一个数据列表,我想在我的视图页面的表结构中显示它。 我尝试了以下代码,但它显示了一些错误

  

“类不包含GetEnumerator的定义”

控制器

public ActionResult data(Message msg,IEnumerable<sample> dept)
{
    dbconnection db = new dbconnection();
    sample s = new sample();
    SqlConnection con = new SqlConnection(db.GetconString());
    DataTable dt;   
    List<examplemvc1.Models.sample> datatable = new List<sample>();
    dt = db.BuildDT("select * from MVCsample");
    foreach (DataRow row in dt.Rows)
    {
        s.FirstName = Convert.ToString(row["First Name"]);
        s.LastName = Convert.ToString(row["Last Name"]);
        s.Address = Convert.ToString(row["Address"]);
        s.PhoneNumber = Convert.ToString(row["PhoneNumber"]);
        s.Location = Convert.ToString(row["Location"]);
        datatable.Add(s);
        dept = datatable;  
    }
    ViewBag.tabledata = dept;
    return View(dept) ;
}

模型

public class sample
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Address { get; set; }
    public string PhoneNumber { get; set; }
    public string Location { get; set; }
    public string tabledata { get; set; }
}

public class Message
{
    public IEnumerable<sample> sampleList { get; set; }
    public string MessageText { get; set; }
    public string MessageFrom { get; set; }
}

查看

@model examplemvc1.Models.sample

@foreach (var data in Model)
{
    <table><tr><td>@data.FirstName</td></tr></table>
}

更新 这就是我整个视图的样子

@model List<examplemvc1.Models.sample>
@{
    ViewBag.Title = "Registration Form";
}
<head>
    <script type="text/javascript" src="../../Scripts/jquery-1.7.1.min.js"></script>
    <link href="../../Style/sample.css" rel="stylesheet" type="text/css" />
    <script src="../../Scripts/samplescript.js" type="text/javascript"></script>
</head>
<h2>
    Registration Form </h2>
   <body>

  <table>
 <tr>
 <th>
   First Name
 </th>
 </tr>

@foreach (var data in Model)
{
    <tr><td>@data.FirstName</td></tr>
}
</table>



@using (Html.BeginForm())
{

    <table id="table1">
    <tr>
         <td> 

             @Html.Label("Enter FirstName", new { @class = "standard_label_style" })
        </td>
         <td>
             @Html.TextBoxFor(a => a.FirstName, new { @class = "class1", title = "Enter FirstName", id = "NameBox", placeholder = "Enter name", onkeydown = "return TextField(event)" })
          <span class="errorMessage"></span>
           @if (!ViewData.ModelState.IsValid)
           {       
                <span class="field-validation-error">
                @ViewData.ModelState["FirstName"].Errors[0].ErrorMessage</span>
           }     
    </td>
    </tr>


    <tr>
    <td>
    @Html.Label("Enter LastName", new { @class = "standard_label_style" })
    </td>
    <td>

    @Html.TextBoxFor(a => a.LastName, new { @class = "class1", placeholder = "Enter name", id = "LastNameBox", title = "Enter Lastname", onkeydown = "return TextField(event); " })
        <span class="errorMessage"></span>
       </td>
    </tr>
    <tr>
    <td>
     @Html.Label("Enter Address", new { @class = "standard_label_style" })
     </td>
     <td>
      @Html.TextBoxFor(a => a.Address, new { @class = "class1", id = "AddressBox", placeholder = "Enter name", title = "Enter Address" })
    <span class="errorMessage"></span>
   </td>
    </tr>
    <tr>
   <td>
    @Html.Label("Enter PhoneNumber", new { @class = "standard_label_style" })
    </td>
    <td>
    @Html.TextBoxFor(a => a.PhoneNumber, new { @class = "class1", id = "PhoneBox", placeholder = "Enter name", title = "Enter Phonenumber", onkeydown = "return ValidateNumber(event);" })
    <span class="errorMessage"></span>
    </td>
  </tr>
  <tr>
  <td>
    @Html.Label("Enter Location", new { @class = "standard_label_style" })
    </td><td>
      @Html.TextBoxFor(a => a.Location, new { @class = "class1", id = "LocationBox", placeholder = "Enter name", title = "Enter Location" })
      <span class="errorMessage"></span>
      </td>
     </tr>
   </table>
    <input type="button" id="btnSave"  value="Register"/>
     <input type="button" value="Clear"/>
     <input type="button" id="Tabledata" value="Tabledata"/>
    <div id="div1"></div>

   @*@Html.ValidationSummary()*@








   <script type="text/javascript">

       function ValidateNumber(e) {
           var evt = (e) ? e : window.event;
           var charCode = (evt.keyCode) ? evt.keyCode : evt.which;
           if (charCode > 31 && (charCode < 48 || charCode > 57)) {
               return false;
           }
           return true;
       };
       function TextField(e) {
           var evt = (e) ? e : window.event;
           var charCode = (evt.keyCode) ? evt.keyCode : evt.which;
           if (charCode > 31 && (charCode < 48 || charCode > 56)) {
               return true;
           }
           else if (charCode == 8 || charCode == 9) {
               return true;
           }
           return false

       };


   </script>

}
   </body>

错误显示在我的视图代码中,实际上我不知道如何在视图页面中获取这些值。我是mvc的新手。请帮我解决这个问题。任何帮助将不胜感激。

“更新”

我已经在Stackoverflow的帮助下解决了我的问题以下是我的正确代码

控制器

 public ActionResult data()
        {
            SomeViewModel model = new SomeViewModel();
            dbconnection db = new dbconnection();
            SqlConnection con = new SqlConnection(db.GetconString());
            DataTable dt = db.BuildDT("select * from MVCsample");
            foreach (DataRow row in dt.Rows)
            {
                sample s = new sample();
                s.FirstName = Convert.ToString(row["First Name"]);
                s.LastName = Convert.ToString(row["Last Name"]);
                s.Address = Convert.ToString(row["Address"]);
                s.PhoneNumber = Convert.ToString(row["PhoneNumber"]);
                s.Location = Convert.ToString(row["Location"]);
                model.samples.Add(s);
            }
            return View(model);
        }

模型

namespace examplemvc1.Models
{
    public class sample
    {

        public string FirstName { get; set; }

        public string LastName { get; set; }

        public string Address { get; set; }


        public string PhoneNumber { get; set; }

        public string Location { get; set; }
         public string tabledata { get; set; }

    }
    public class Message
    {
        public IEnumerable<sample> sampleList { get; set; }
        public string MessageText { get; set; }
        public string MessageFrom { get; set; }
    }
    public class SomeViewModel
    {
        public SomeViewModel()
        {
            samples = new List<sample>();
            sample = new sample();
        }
        public List<sample> samples { get; set; }
        public sample sample { get; set; }
    }
}

查看

@model examplemvc1.Models.SomeViewModel

// ................       

@foreach (var data in Model.samples)
{
    <tr><td>@data.FirstName</td>
     <td>@data.LastName</td>
     <td>@data.Address</td>
     <td>@data.PhoneNumber</td>
     <td>@data.Location</td></tr>
}
</table>

请看下面的Stephen Muecke的答案,他已经非常清楚地解释了背景

3 个答案:

答案 0 :(得分:2)

您正在查看同时显示sample列表以及新sample的表单。首先创建一个视图模型来表示您想要显示/编辑的内容

public class SampleVM
{
  public SampleVM
  {
      SampleCollection = new List<sample>
  }
  public List<sample> SampleCollection { get; set; }
  public sample NewSample { get; set; }
}

在您的控制器中将代码修改为

public ActionResult data()
{
    SampleVM model = new SampleVM();
    dbconnection db = new dbconnection();
    SqlConnection con = new SqlConnection(db.GetconString());
    DataTable dt = db.BuildDT("select * from MVCsample");
    foreach (DataRow row in dt.Rows)
    {
        sample s = new sample();
        s.FirstName = Convert.ToString(row["First Name"]);
        s.LastName = Convert.ToString(row["Last Name"]);
        s.Address = Convert.ToString(row["Address"]);
        s.PhoneNumber = Convert.ToString(row["PhoneNumber"]);
        s.Location = Convert.ToString(row["Location"]);
        model.SampleCollection.Add(s);
    }
    return View(model);
}

注意:

  1. 从GET方法中删除参数。除了你的事实 不要使用它们,所以它们毫无意义,即使你要尝试也是如此 将这些对象传递给方法,绑定将失败并且 集合将为null(如果您要构造正确的 查询字符串使其工作,它将是如此长的几乎 肯定会抛出异常)
  2. 您需要在sample循环内初始化新的foreach (您的代码只初始化了一个对象,每个循环都更新了它 属性到当前行,所以你最终会得到多个 同一个对象的引用,都匹配最后一个的值 你表中的一行)
  3. 无需将模型作为ViewBag属性传递(其中) 已使用return View(model);
  4. 传递给视图

    将视图修改为

    @model SampleVM
    ....
    <table>
        @foreach(var sample in Model.SampleCollection)
            <tr>
                <td>@sample .FirstName</td>
            </tr>
        }
    </table>
    @Html.BeginForm())
    {
      @Html.LabelFor(m => m.NewSample.FirstName, "Enter FirstName", new { @class = "standard_label_style" })
      @Html.TextBoxFor(m => m.NewSample.FirstName, @class = "class1", placeholder = "Enter name", title = "Enter Lastname")
      @Html.ValidationMessageFor(m => m.NewSample.FirstName)
    }
    ....
    <input type="submit" id="btnSave"  value="Register"/>
    

    注意:

    1. 标签元素,用于将元素与控件相关联。您的 用法生成<label for="Enter_FirstName">,但你没有 用id="Enter_FirstName"控制。你应该优先考虑 [Display(Name = "Enter FirstName")]在酒店,但不是 使用强类型助手
    2. 使用@Html.ValidationMessageFor()呈现ModelState错误, 虽然在你的情况下你所有的属性都是字符串而你不是 有任何验证属性,所以永远不会有任何错误,所以 它有点无意义
    3. html帮助器生成id属性。很少需要 覆盖它。停止通过行为污染您的标记并学习 使用Unobtrusive Javascript
    4. 您的表单未包含提交按钮

答案 1 :(得分:1)

问题是您的模型属于examplemvc1.Models.sample类型,而您必须将List<examplemvc1.Models.sample>的对象传递给视图:

 return View(datatable) ;

你的行动:

List <examplemvc1.Models.sample> datatable = new List<sample>();

dt = db.BuildDT("select * from MVCsample");
    foreach (DataRow row in dt.Rows)
    {
       s.FirstName = Convert.ToString(row["First Name"]);
       s.LastName = Convert.ToString(row["Last Name"]);
       s.Address = Convert.ToString(row["Address"]);
       s.PhoneNumber = Convert.ToString(row["PhoneNumber"]);
       s.Location = Convert.ToString(row["Location"]);
       datatable.Add(s);
    }


    return View(datatable);  // passing list to view

并在View中将模型设置为List<examplemvc1.Models.sample>

@model List<examplemvc1.Models.sample>

现在按照你的方式迭代:

<table>
 <thead>
 <tr><th>First Name</th></tr>
 </thead>
 <tbody>
@foreach (var data in Model)
{
    <tr><td>@data.FirstName</td></tr>
}
</tbody>
</table>

答案 2 :(得分:1)

问题在于您的模型指令。

应该是

@model IEnumerable<examplemvc1.Models.sample>

而不是

@model examplemvc1.Models.sample

注意:您正在进行几次dept = datatable;的作业,而不是像这样更新代码。

public ActionResult data(Message msg,IEnumerable<sample> dept)
    {

        dbconnection db = new dbconnection();
        sample s = new sample();
       SqlConnection con = new SqlConnection(db.GetconString());
        DataTable dt;

            List <examplemvc1.Models.sample> datatable = new List<sample>();

           dt = db.BuildDT("select * from MVCsample");
           foreach (DataRow row in dt.Rows)
           {
               s.FirstName = Convert.ToString(row["First Name"]);
               s.LastName = Convert.ToString(row["Last Name"]);
               s.Address = Convert.ToString(row["Address"]);
               s.PhoneNumber = Convert.ToString(row["PhoneNumber"]);
               s.Location = Convert.ToString(row["Location"]);
               datatable.Add(s);

              //dept = datatable;

           }
            ViewBag.tabledata = datatable;

            return View(datatable) ;
    }

<强>更新 在这种情况下,您需要首先创建viewmodel并将其实例作为模型传递给它。

public class SomeViewModel
{
    public SomeViewModel()
    {
        samples = new List<sample>();
        sample = new sample();
    }
    public List<sample> samples {get; set;}
    public sample sample {get; set;}
}

并在模型声明中

@model namespace.SomeViewModel

然后在控制器中如下。

public ActionResult data(Message msg,IEnumerable<sample> dept)
{
    dbconnection db = new dbconnection();
    sample s = new sample();
    SqlConnection con = new SqlConnection(db.GetconString());
    DataTable dt;   
    List<examplemvc1.Models.sample> datatable = new List<sample>();
    dt = db.BuildDT("select * from MVCsample");
    foreach (DataRow row in dt.Rows)
    {
        s.FirstName = Convert.ToString(row["First Name"]);
        s.LastName = Convert.ToString(row["Last Name"]);
        s.Address = Convert.ToString(row["Address"]);
        s.PhoneNumber = Convert.ToString(row["PhoneNumber"]);
        s.Location = Convert.ToString(row["Location"]);
        datatable.Add(s);
        dept = datatable;  
    }
    ViewBag.tabledata = dept;
    SomeViewModel vm = new SomeViewModel();
    vm.samples = datatable;
    vm.sample = //somesample instance here you want to edit.

    return View(vm) ;
}

并在视图中,您将获得vm迭代vm.samples

的实例
@foreach (var data in Model.samples)
{
    <tr><td>@data.FirstName</td></tr>
}

并在其余视图中执行以下操作:

@Html.TextBoxFor(a => a.sample.FirstName, new { @class = "class1", title = 
"Enter FirstName", id = "NameBox", placeholder = "Enter name", onkeydown = 
"return TextField(event)" })