我如何绑定一个DataTable到模型,然后在MVC一个DropDownList? [英] How do I bind a datatable to model and then to a dropdownlist in mvc?

查看:137
本文介绍了我如何绑定一个DataTable到模型,然后在MVC一个DropDownList?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我感到非常如何做到这一点困惑,我已经看到了这些:<一href=\"http://stackoverflow.com/questions/8549147/how-to-bind-datatable-to-html-dropdownlistfor-in-asp-net-mvc3\">reference类似的问题1 &安培; <一href=\"http://stackoverflow.com/questions/10189576/how-to-bind-a-datatable-to-a-dropdownlist-using-mvc-razor\">reference类似的问题2 这两个问题的回答没有解释我是如何结合实际的数据表变量模型,因为它们被指定为DropDownList的部分了。

我一直在使用这两种方法的尝试:其一是列表从模型到DataTable串和其他绑定是创建一个字符串的模型类,我在模型中创建的字符串对象的列表绑定控制器。但我的问题仍保留在该数据表中的变量和模型项它被传递给在foreach内模具。

所以,我应该如何使用模型准确到DataTable绑定到DropDownList的?

控制器:

  BFProj2.Models.OurColumns O =新Models.OurColumns();
                o.DCResults =新的List&LT;串GT;();                清单&LT; OurColumns&GT; S =新的List&LT; OurColumns&GT;();
                对于(INT Y = 0; Y&LT; csvData.Columns.Count; Y ++)
                {
                    字符串DC = csvData.Columns [Y] .ColumnName.ToString();
                    //当在模型中创建的列表。
                    o.DCResults.Add(dc.ToString());                    //当在控制器被创建的列表。
                   的foreach(OurColumns DC1在S)
                   {
                       dc1.result = DC;
                   }                }                //仍处于试...                //
                //
                //这里前者结合到数据库开始的。
                //
                //
            }
            赶上(异常前)
            {
                //返回视图(错误+ ex.GetType()的ToString());
            }
            // csvData是{}表1
        }
        返回查看();
    }

csvData是数据表。

型号:

 命名空间BFProj2.Models
{
公共类OurColumns
{
    // [显示名称(密码)]
    公共字符串密码{搞定;组; }    // [显示名称(电子邮件)]
    公共字符串电子邮件{获得;组; }    // [DisplayName的(注解)]
    公共字符串评论{搞定;组; }    // [显示名称(用户名)]
    公共字符串用户名{获得;组; }    // [显示名称(名字)]
    公共字符串名字{获得;组; }    // [显示名称(姓氏)
    公共字符串名字{获得;组; }    // [显示名称(上次活动日期)]
    公众的DateTime? LASTUPDATEDATE {搞定;组; }    // [显示名称(标题)
    公共字符串名称{搞定;组; }    // [显示名称(抽象的数字)]
    公众诠释AbstrNum {搞定;组; }    // [显示名称(海报标题)]
    公共字符串PosterTitle {搞定;组; }    // [显示名称(车间)]
    公共字符串车间{搞定;组; }    // [显示名称(关键字)
    公共字符串关键词{搞定;组; }    // [显示名称(机构)]
    公共字符串机构{搞定;组; }    // [显示名称(合作邮件)]
    公共字符串CollabEmail {搞定;组; }    公共字符串SESSIONDATE {搞定;组; }    // [DisplayName的(DCResults)]
    公开名单&LT;串GT; DCResults {搞定;组; }    公共字符串结果{搞定;组; }公开名单&LT;串GT; SelectedDCResults {搞定;组; }
}
//公共类SelectedDCResults
// {
//公共字符串结果{搞定;组; }
//}
}

查看:

  @model BFProj2.Models.OurColumns@ {
    ViewBag.Title =Importcsv;
    布局=〜/查看/共享/ _Layout.cshtml
}&LT; H2&GT;导入CSV&LT; / H&GT;@ Html.EditorFor(型号=&GT; model.FirstName)
&LT; D​​IV CLASS =显示字段&GT;
@ Html.DropDownListFor(M = GT; m.result,新的SelectList(Model.DCResults))
&LT; / DIV&GT;@ Html.EditorFor(型号=&GT; model.LastName)
&LT; D​​IV CLASS =显示字段&GT;
@ Html.DropDownListFor(M = GT; m.SelectedDCResults,新的SelectList(Model.DCResults))
&LT; / DIV&GT;@ Html.EditorFor(型号=&GT; model.Email)
&LT; D​​IV CLASS =显示字段&GT;
@ Html.DropDownListFor(M = GT; m.SelectedDCResults,新的SelectList(Model.DCResults))
&LT; / DIV&GT;@ Html.EditorFor(型号=&GT; model.UserName)
&LT; D​​IV CLASS =显示字段&GT;
@ Html.DropDownListFor(M = GT; m.SelectedDCResults,新的SelectList(Model.DCResults))
&LT; / DIV&GT;@ Html.EditorFor(型号=&GT; model.Comment)
&LT; D​​IV CLASS =显示字段&GT;
@ Html.DropDownListFor(M = GT; m.SelectedDCResults,新的SelectList(Model.DCResults))
&LT; / DIV&GT;@ Html.EditorFor(型号=&GT; model.Title)
&LT; D​​IV CLASS =显示字段&GT;
@ Html.DropDownListFor(M = GT; m.SelectedDCResults,新的SelectList(Model.DCResults))
&LT; / DIV&GT;@ Html.EditorFor(型号=&GT; model.Workshop)
&LT; D​​IV CLASS =显示字段&GT;
@ Html.DropDownListFor(M = GT; m.SelectedDCResults,新的SelectList(Model.DCResults))
&LT; / DIV&GT;@ Html.EditorFor(型号=&GT; model.AbstrNum)
&LT; D​​IV CLASS =显示字段&GT;
@ Html.DropDownListFor(M = GT; m.SelectedDCResults,新的SelectList(Model.DCResults))
&LT; / DIV&GT;@ Html.EditorFor(型号=&GT; model.PosterTitle)
&LT; D​​IV CLASS =显示字段&GT;
@ Html.DropDownListFor(M = GT; m.SelectedDCResults,新的SelectList(Model.DCResults))
&LT; / DIV&GT;@ Html.EditorFor(型号=&GT; model.Keywords)
&LT; D​​IV CLASS =显示字段&GT;
@ Html.DropDownListFor(M = GT; m.SelectedDCResults,新的SelectList(Model.DCResults))
&LT; / DIV&GT;@ Html.EditorFor(型号=&GT; model.Institution)
&LT; D​​IV CLASS =显示字段&GT;
@ Html.DropDownListFor(M = GT; m.SelectedDCResults,新的SelectList(Model.DCResults))
&LT; / DIV&GT;@ Html.EditorFor(型号=&GT; model.CollabEmail)
&LT; D​​IV CLASS =显示字段&GT;
@ Html.DropDownListFor(M = GT; m.SelectedDCResults,新的SelectList(Model.DCResults))
&LT; / DIV&GT;&LT;! - 到UserInput表添加会议日期字符串格式 - &GT;@ Html.EditorFor(型号=&GT; model.SessionDate)
&LT; D​​IV CLASS =显示字段&GT;
@ Html.DropDownListFor(M = GT; m.SelectedDCResults,新的SelectList(Model.DCResults))
&LT; / DIV&GT;


解决方案

首先,获得这个code你的控制器。在MVC控制器应该是薄 - 他们的责任应该搞清楚视图渲染它并通过数据和从视图和业务层。
其次,你的看法是强类型的OurColumns对象OurColumns对象的实例不会传递的看法。它看起来像你需要有DCResults为你的DropDownList和一个字符串来捕捉选定值的集合的视图模型。这是不是有一个单独的选定项严格必要的,但我喜欢它是如何简化code - 这是一个ViewModel毕竟

 公共类视图模型{
        公共字符串名字{获得;组; }
        公共字符串名字{获得;组; }
        公共字符串电子邮件{获得;组; }
        公开名单&LT;串GT; DCResults {搞定;组; }
        公共字符串SelectedDCResult {搞定;组; }
    }

您控制器应负责对GET请求创建视图模型和分析视图模型到业务对象(或过去沿以更加分层应用服务)。

 公众的ActionResult获得()
{
    VAR模型=新的ViewModel {
        DCResults = this.DcResultRepos.DCResults
    };
    返回查看(模型);
}公众的ActionResult邮政(视图模型模型){
    如果(ModelState.IsValid){
        //做一点事
    }
    返回视图(别论);
}

如果你不使用持久存储的ORM对象绑定,那么您将需要创建自己的,在另一个类,所以你可以抽象掉,从WebUI的结合。对于previous例如,我用下面的签名:

 私有类DCResultRepository {
    公开名单&LT;串GT; DCResults {搞定; }
}

在GET(或辅助法)的身体,你可以处理你的数据表和使用收益的回报来创建一个IEnumerable,它会让你在你的控制器使用Linq。像这样的:

 私人数据表的表;
公共IEnumerable的&LT;模型与GT; DCResults {
    获得{
        //做一些事情来获得数据表
        的foreach(在table.Rows VAR行){
            产量返回新模型(){
                //初始化值
            };
        }
    }
}

I am very confused by how to accomplish this, I have seen these: reference to similar question 1 & reference to similar question 2 None of these two question answers explains how I bind the actual datatable variable to the model since they are specified to the dropdownlist part more.

I have tried using two methods: One was to bind a list from a model to the datatable string and the other was to create a model class with a string that I bind by creating a list of the string object in the model in the controller. But my problem remains in that the datatable variables and the model item it is passed to dies inside the foreach.

So how should I use the model correctly to bind the datatable to the dropdownlist?

Controller:

 BFProj2.Models.OurColumns o = new Models.OurColumns();


                o.DCResults = new List<string>();

                List<OurColumns> s = new List<OurColumns>();


                for(int y = 0; y <csvData.Columns.Count; y++)
                {
                    string dc = csvData.Columns[y].ColumnName.ToString();


                    //When the list is created in the model.
                    o.DCResults.Add(dc.ToString());

                    //when the list is created in the controller.
                   foreach(OurColumns dc1 in s)
                   {
                       dc1.result = dc;


                   }

                }

                //Still in try...

                //
                //
                // Here the former binding to the database began.
                //
                //


            }
            catch (Exception ex)
            {
                //return View("Error"+ ex.GetType().ToString());
            }
            //csvData is {Table1}
        }
        return View();
    }

csvData is the datatable.

Model:

namespace BFProj2.Models
{
public class OurColumns
{
    //[DisplayName("Password")]
    public string Password { get; set; }

    //[DisplayName("Email")]
    public string Email { get; set; }

    //[DisplayName("Comment")]
    public string Comment { get; set; }

    //[DisplayName("Username")]
    public string UserName { get; set; }

    //[DisplayName("Firstname")]
    public string FirstName { get; set; }

    //[DisplayName("Lastname")]
    public string LastName { get; set; }

    //[DisplayName("Last activity date")]
    public DateTime? LastUpdateDate { get; set; }

    //[DisplayName("Title")]
    public string Title { get; set; }

    //[DisplayName("Abstract number")]
    public int AbstrNum { get; set; }

    //[DisplayName("Poster title")]
    public string PosterTitle { get; set; }

    //[DisplayName("Workshop")]
    public string Workshop { get; set; }

    //[DisplayName("Keywords")]
    public string Keywords { get; set; }

    //[DisplayName("Institution")]
    public string Institution { get; set; }

    //[DisplayName("Collaboration email")]
    public string CollabEmail { get; set; }

    public string SessionDate { get; set; }

    //[DisplayName("DCResults")]
    public List<string> DCResults { get; set; }

    public string result { get; set; }

public List<string> SelectedDCResults { get; set; }
}
//public class SelectedDCResults
//{
//    public string result { get; set; }
//}
}    

View:

@model BFProj2.Models.OurColumns

@{
    ViewBag.Title = "Importcsv";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<h2>Import CSV</h2>

@Html.EditorFor(model => model.FirstName)
<div class="display-field">
@Html.DropDownListFor(m => m.result, new SelectList(Model.DCResults))
</div>

@Html.EditorFor(model => model.LastName)
<div class="display-field">
@Html.DropDownListFor(m => m.SelectedDCResults, new SelectList(Model.DCResults))
</div>

@Html.EditorFor(model => model.Email)
<div class="display-field">
@Html.DropDownListFor(m => m.SelectedDCResults, new SelectList(Model.DCResults))
</div>

@Html.EditorFor(model => model.UserName)
<div class="display-field">
@Html.DropDownListFor(m => m.SelectedDCResults, new SelectList(Model.DCResults))
</div>

@Html.EditorFor(model => model.Comment)
<div class="display-field">
@Html.DropDownListFor(m => m.SelectedDCResults, new SelectList(Model.DCResults))
</div>

@Html.EditorFor(model => model.Title)
<div class="display-field">
@Html.DropDownListFor(m => m.SelectedDCResults, new SelectList(Model.DCResults))
</div>

@Html.EditorFor(model => model.Workshop)
<div class="display-field">
@Html.DropDownListFor(m => m.SelectedDCResults, new SelectList(Model.DCResults))
</div>

@Html.EditorFor(model => model.AbstrNum)
<div class="display-field">
@Html.DropDownListFor(m => m.SelectedDCResults, new SelectList(Model.DCResults))
</div>

@Html.EditorFor(model => model.PosterTitle)
<div class="display-field">
@Html.DropDownListFor(m => m.SelectedDCResults, new SelectList(Model.DCResults))
</div>

@Html.EditorFor(model => model.Keywords)
<div class="display-field">
@Html.DropDownListFor(m => m.SelectedDCResults, new SelectList(Model.DCResults))
</div>

@Html.EditorFor(model => model.Institution)
<div class="display-field">
@Html.DropDownListFor(m => m.SelectedDCResults, new SelectList(Model.DCResults))
</div>

@Html.EditorFor(model => model.CollabEmail)
<div class="display-field">
@Html.DropDownListFor(m => m.SelectedDCResults, new SelectList(Model.DCResults))
</div>

<!--Add session date to UserInput table as string format-->

@Html.EditorFor(model => model.SessionDate)
<div class="display-field">
@Html.DropDownListFor(m => m.SelectedDCResults, new SelectList(Model.DCResults))
</div>

解决方案

First, get this code out of your controller. In MVC controllers should be thin – their responsibility should be figuring out which View to render and passing data to and from the Views and the business layer. Second, your View is strongly typed to the OurColumns object an instance of the OurColumns object is never passed the view. It looks like you need a ViewModel that has a collection of DCResults for your DropDownList and a string to capture the selected value. It is not strictly necessary to have a separate "Selected" item, but I like how it simplifies code – it’s a ViewModel after all.

public class ViewModel {
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string Email { get; set; }
        public List<string> DCResults { get; set; }
        public string SelectedDCResult { get; set; }
    }

Your controller should be responsible for creating the View Model on the GET request and parse the ViewModel into the Business Object (or past that along to a service in a more layered application).

public ActionResult Get()
{
    var model = new ViewModel {
        DCResults = this.DcResultRepos.DCResults
    };
    return View(model);
}

public ActionResult Post(ViewModel model) {
    if (ModelState.IsValid) {
        //do something 
    }
    return View("Another View");
}

If you are not using an ORM for persistent storage to object binding, then you will need to create your own, in another class so you can abstract away that binding from the WebUI. For the previous example, I used the following signature:

private class DCResultRepository {
    public List<string> DCResults { get; }
}

In the body of the get (or helper method) you could process your DataTable and use yield return to create an IEnumerable that would allow you to use Linq in your controller. Like this:

private DataTable table;
public IEnumerable<Model> DCResults {
    get {
        //do something to get datatable
        foreach(var row in table.Rows){
            yield return new Model(){
                //initialize values
            };
        }
    }
}

这篇关于我如何绑定一个DataTable到模型,然后在MVC一个DropDownList?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆