Tim Verhees
Tim Verhees

Reputation: 31

How do I get a search for an int entry working in MVC EF?

I'm trying to search for a 4 number postal number within MVC and the code I have doesn't work, what is stopping it from working?

So far I've tried many different solutions on the web, but none have been succesful. Not even when trying to convert it to a string, which only created a big error so I'm honestly abandoning that.

public ActionResult Index(int search)
        {
            var storingen = from s in db.tbl_Storing
                            select s;
            if (search != null)
            {
                storingen = storingen.Where(s => s.postcode_nr == (search));
            }
            return View(storingen.ToList());
        }

That is from my controller, this is from my actual view:

Zoek op postcode: @Html.TextBox("search")
    <input type="submit" value="Search" />

Now when I actually fill in one of the two currently present numbers and hit search nothing happens, no error, nothing.

Upvotes: 0

Views: 144

Answers (1)

Hien Nguyen
Hien Nguyen

Reputation: 18975

You can change from int to int? and check search is null in your controller.

If user enter text like abc, search param will pass null to controller.

[HttpGet]
public ActionResult Index(int? search)
        {
            // check search null before query

            var storingen = from s in db.tbl_Storing
                            select s;
            if (search != null)
            {
                storingen = storingen.Where(s => s.postcode_nr == (search));
            }
            return View(storingen.ToList());
}

And this is sample for cshtml

 <form action="/YourController/Index" method="get">
        Zoek op postcode: @Html.TextBox("search")
        <input type="submit" value="Search" />
    </form>

Upvotes: 0

Related Questions