D
D
Denis2015-12-19 15:36:41
ASP.NET
Denis, 2015-12-19 15:36:41

How to display a List in a View if the list is still null?

Good afternoon!
I'm mastering asp.net mvc, a completely newbie developer.
My task is this: From View I get some kind of string, I look for a match in the database and display the result below.
Here is the controller code:

[HttpPost]
        public ActionResult Index(string surname)
        {
            var allDriver = db.Table.Where(a => a.surname.Contains(surname)).ToList();
            if (allDriver.Count != 0)
            {
                ViewBag.Drivers = allDriver;
                return View();
            }
            return View();
        }

And here is the View code
<div>
    @using (Html.BeginForm())
    {
        @Html.TextBoxFor(x=>x.surname);
        <input type="submit" value="Найти"/>
    }

    @foreach (var x in @ViewBag.Drivers)
    {
        <p>@x</p>
    }

</div>

Now the application crashes with an error that the object reference does not point to an object instance.
I understand that this is due to the fact that so far there is nothing in this @ViewBag.Drivers, tk. we have not yet entered anything into the line and did not look for it.
Please tell me how to do it right? Maybe I have a fundamentally wrong approach? Thanks in advance

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry Kovalsky, 2015-12-19
@darkmayers

1) Master the concept of Model. Create a class one of whose fields will be your Drivers. Create a strongly typed View for this class. (At the same time, learn how to load this list asynchronously)
2) An easier way "on the forehead"

@if(ViewBag.Drivers!=null)
{foreach (var x in ViewBag.Drivers)
    {
        <p>@x</p>
    }
}

In general, I recommend that you do not get used to using ViewBag, but rather master strongly typed View, Partial View, and so on. ViewBag is suitable for carrying short messages. Dragging objects around to display in the interface is bad practice, forcing you to invent crutches, which you actually asked about.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question