如何将数据表绑定到模型,然后绑定到mvc中的下拉列表? [英] How do I bind a datatable to model and then to a dropdownlist in mvc?

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

问题描述

我很困惑如何完成这个,我已经看到这些:参考类似的问题1 & 参考类似问题2 无这两个问题答案解释了我如何将实际的datatable变量绑定到模型,因为它们更多地被指定给下拉列表部分。

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.

我尝试过使用两种方法:一种是将列表从模型绑定到数据字符串,另一个是通过在控制器中的模型中创建一个字符串对象的列表来创建一个包含我绑定的字符串的模型类。但是我的问题仍然在于,datatable变量和它被传递的模型项目在foreach内部死亡。

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.

那么我该如何正确地使用模型将datatable绑定到下拉列表?

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

控制器: p>

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是数据。

csvData is the datatable.

模型:

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; }
//}
}    

查看:

@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>


推荐答案

首先,将此代码从控制器中取出。在MVC控制器应该很薄 - 他们的责任应该是弄清楚哪个视图渲染和传递数据到和从视图和业务层。
其次,您的View对OurColumns对象强类型,OurColumns对象的一个​​实例从不传递到该视图。看起来您需要一个ViewModel,它具有您的DropDownList的DCResults集合和一个用于捕获所选值的字符串。没有必要单独的Selected项目,但我喜欢它如何简化代码 - 毕竟它是一个ViewModel。

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; }
    }

您的控制器应负责在GET请求上创建View Model,将ViewModel解析为业务对象(或者在更为分层的应用程序中的服务之前)。

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");
}

如果您没有使用ORM来持久存储来对象绑定,那么你将需要创建自己的另一个类,以便您可以从WebUI中抽取该绑定。对于前面的例子,我使用了以下签名:

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; }
}

在get(或帮助方法)的正文中,您可以处理DataTable并使用yield yield来创建一个IEnumerable,可以让您在控制器中使用Linq。像这样:

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
            };
        }
    }
}

这篇关于如何将数据表绑定到模型,然后绑定到mvc中的下拉列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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