Bind DropDownList using ModelView and DataTable in ASP.Net MVC

Last Reply 4 months ago By dharmendr

Posted 4 months ago

hi,

I use Modelview for binding dropdownlist and bind data into table below is code:

public ActionResult List()
{
    var model = new SearchViewModel();
    model.Ostans = PopulateOstan();
    return View(model);
}

here I use viewmodel to bind data in Dropdownlist

@Html.DropDownListFor(model => model.Ostans, Model.Ostans, "Please select")

Now in this page I want to bind Table from database to show Costumers information in table I have these codes for binding data from database

DataTable dt = new DataTable();
string constr = ConfigurationManager.ConnectionStrings["ConString"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
    string query = "SELECT * FROM Customers";
    using (SqlCommand cmd = new SqlCommand(query))
    {
        cmd.Connection = con;
        using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
        {
            sda.Fill(dt);
        }
    }
} 
return View(dt);

now I want use above code in below action

public ActionResult List()
{
    var model = new SearchViewModel();
    model.Ostans = PopulateOstan();
    return View(model);
}

but I dont know how I can use Datatable and Viewmodel together in Action

Best Regards

Neda

You are viewing reply posted by: dharmendr 4 months ago.
Posted 4 months ago

Hi nedash,

Check this example. Now please take its reference and correct your code.

Model

public class SearchViewModel
{
    public int Id { get; set; }
    public DataTable Ostans { get; set; }
}

Controller

public class HomeController : Controller
{
    // GET: /Home/
    public ActionResult Index()
    {
        var model = new SearchViewModel();
        model.Ostans = PopulateOstan();
        return View(model);
    }

    private DataTable PopulateOstan()
    {
        DataTable dt = new DataTable();
        dt.Columns.AddRange(new DataColumn[3] { new DataColumn("Id", typeof(int)),
                        new DataColumn("Name", typeof(string)),
                        new DataColumn("Country",typeof(string)) });
        dt.Rows.Add(1, "John Hammond", "United States");
        dt.Rows.Add(2, "Mudassar Khan", "India");
        dt.Rows.Add(3, "Suzanne Mathews", "France");
        dt.Rows.Add(4, "Robert Schidner", "Russia");

        return dt;
    }
}

View

<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<_DataTable_ViewModel_MVC.Models.SearchViewModel>" %>

<%@ Import Namespace="System.Data" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Index</title>
</head>
<body>
    <%:Html.DropDownListFor(model => model.Ostans, (new SelectList(Model.Ostans.AsDataView(), "Id", "Name")))%>
</body>
</html>

Screenshot