views:

233

answers:

2

Ok, I've just started learning ASP.NET MVC after being an ASP.NET developer for awhile. I think my main problem I'm having is trying to "unlearn" ASP.NET when developing my MVC projects.

Here's my question: I have a page which has some input fields. These fields are parameters to a search I'm trying to run against a database. The user checks the boxes next to the types of items they want to see and then clicks "Search". Very simple stuff.

I'm having trouble wrapping my mind around how exactly to "postback" to the page to display the results. Is it better to use jQuery and serialize the form? Do I use my Entity Framework models I've created? What's the best way to go about

I'm really excited about MVC and the control it gives me, but I need to get over these initial obstacles if I ever want to "sell" it to my boss as the way to develop all of our web apps. Thanks for reading!

+2  A: 

If your inputs are inside html form element (different story if javascript is involved) - you can use default model binding (it binds route values and querystring parameters too).

<form ...>
    <input type="text" name="query" />
    <input type="submit" .../>
</form>

on submit it will automagically bind form values (by name) to action parameters:

public ActionResult PerformSearch(string query)
{
    //whatever
}

In your case - i suspect you got inputs as checkboxes. Something like this should work:

<form...>

    <input type="checkbox" name="p" value="value1" />
    <input type="checkbox" name="p" value="value2" />
    <input type="checkbox" name="p" value="value3" />
    <input type="checkbox" name="p" value="value4" />
    <input type="checkbox" name="p" value="value5" />
</form>

public ActionResult PerformSearch(string[] p)
{
    //whatever
}

Only - if (form method == "GET"), URL won't look nicely. :)

To show results, make a model for your view in action and just show it through view:

public ActionResult PerformSearch(string[] p)
{
    var model = _searchService(p);
    return View("Results", model);   
}

Views/Results.aspx

<% foreach(var bar in Model){ %>
    <%= bar.Name %>
<%}%>

P.s. When considering AJAX calls, always remember that you are loosing ability to show URL + search engines don't understand JS.

Arnis L.
+1  A: 

If you haven't already, consider taking a look at the NerdDinner Tutorial featured in Professional ASP.NET MVC 1.0 by Rob Conery, Scott Hanselman, Phil Haack, and Scott Guthrie. It contains a great demonstration of many of the features of ASP.NET MVC including performing a search and returning the data both through a full page post and also asynchronously using JSON.

Nathan Taylor
Why was this down voted?
Nathan Taylor