Abid Ali
Abid Ali

Reputation: 1747

model is null in MVC

i want to select * data in a table rows and columns in MVC. when i do so, my model is always null. i`m using ADO.NET EDM for this.

my Action Controller code:

public ActionResult SellerView1(string Seller)
    {
        KeywinTest_Project1.tblSeller sellerName = new tblSeller();

        SqlConnection cn = new SqlConnection(@"Data Source=.;Initial Catalog=KeywinDB;Integrated Security=True;Pooling=False");
        string query = "Select * from tblSeller";
        SqlCommand cmd = new SqlCommand(query, cn);
        SqlDataAdapter da = new SqlDataAdapter(cmd);
        DataTable dt = new DataTable();
        da.Fill(dt);
        if (dt.Rows.Count > 0)
        {
            ViewBag.Name = dt.Rows[0]["sellerName"].ToString();
        }
        return View();
    }

my View code:

 @model IEnumerable<KeywinTest_Project1.tblSeller>
@using System.Web.UI.WebControls;

@{
    ViewBag.Title = "SellerView1";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
<body>
    <table>
        @Model = @ViewBag.Name
        @foreach (var item in Model)
        {
            <tr>
                <td>
                    @item.sellerName
                </td>
            </tr>
        }
    </table>
</body>

my Model code:

using System;
using System.Collections.Generic;

public partial class tblSeller
{
    public int id { get; set; }
    public string sellerName { get; set; }
}

what ive done is, ive declared my view as the model class that was generated by my EDM.

What i am doing wrong here? plz guide. Thanks

Upvotes: 0

Views: 76

Answers (2)

Selman Gen&#231;
Selman Gen&#231;

Reputation: 101681

Because you didn't pass your model when you returning your View from Controller

return View();

Here you should pass your ViewModel which is IEnumerable<KeywinTest_Project1.tblSeller>, Like this (fro example):

var sellerList = dt.AsEnumerable() 
                   .Select(d => new tblSeller { sellerName = d["sellerName"].ToString() })
                   .ToList();
return View(sellerList);

Upvotes: 2

cubitouch
cubitouch

Reputation: 1937

You didn't pass the model to the View, like this :

return View(sellerName);

But the sellerName object is not an IEnumerable, so you should rewrite a part of your code in order to make it work.

Upvotes: 0

Related Questions