简体   繁体   中英

How to setup gridview in mvc

I would like to setup gridview under MyTickets tab. How can I set this view to have only tickets from username eg 'testuser' ?

In controller I have below code. Table Zgloszenia is my table where I storing all information about tickets (date,username, id etc)

 public ActionResult MyTickets(Zgloszenia model)
        {
            if (Session["UserID"] != null)
            {
                test dg = new test();
                var item = dg.Zgloszenia.Where(x => x.UsrUsera == model.UsrUsera).SingleOrDefault();
                return View(item);

            }
            else
            {
                return RedirectToAction("Login");
            }

        }

In view I have this code:

@model IEnumerable<Webform.Models.Zgloszenia>
@{
    ViewBag.Title = "MyTickets";
    WebGrid grid = new WebGrid(Model);
}

<h2>MyTickets</h2>

@if (Session["UserID"] != null)
{

    <div>
        Welcome:  <a href="#">@Session["Username"]</a><br />

    </div>
}

@grid.GetHtml(columns: new[] {
    grid.Column("Opis"),
    grid.Column("Priorytet"),
    grid.Column("Srodowisko"),
    grid.Column("NumerTaska"),
    grid.Column("test"),
    grid.Column("Date")
})

When I log in to my app and click Tab "MyTicket" I'm receiving below error:

A data source must be bound before this operation can be performed.

How I can fix this issue and set up view properly ?

Are you working with Visual studio? If yes, you have to make a dataset. (local or online) You do not have a database at the moment so he saves it nowhere.

In your action you are selecting a single item, not a collection to enumerate. On the contrary, the WebGrid expects a collection as a data source, so the way you declared things on the view is fine.

To check if that is indeed the issue, simply remove SingleOrDefault call in your action. If your Where call returns at least one record, you should be able to see it on the page:

test dg = new test();
var items = dg.Zgloszenia.Where(x => x.UsrUsera == model.UsrUsera).ToList();
return View(items);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM