The MVC Framework (now in version 1.0) is Microsoft’s implementation of the MVC software pattern in ASP.Net.
Here, my model is using LINQ to SQL against my empty database called GLOSSARY with one table called TERMS with three columns (Id, Term, Definition). Hopefully, I have kept the scenario simple enough so you can follow me.
In this sample, I have one controller, one view, and one partial view. A partial view is basically an ASP.Net user control (even the same file extension). The partial is a list of terms. The view contains the partial and two identical forms allowing users to filter the list (one POST and one AJAX).
I hope this makes sense to you, because AJAX in MVC is pretty darn easy:
//
// GlossaryController.cs
public ActionResult Index()
{
return View(Models.Term.SelectAll());
}
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(FormCollection collection)
{
// used by non-AJAX form
string _SearchTerm;
_SearchTerm = collection["SearchTerm"];
// don't indicate the partial here, the view will call it
return View(Models.Term.Where(x => x.Term.Contians(_SearchTerm)));
}
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index2(FormCollection collection)
{
// used by AJAX form
string _SearchTerm;
_SearchTerm = collection["SearchTerm"];
// you must indicate the partial here, it's all you want to render
return View("Search", Models.Term.Where(x => x.Term.Contians(_SearchTerm)));
}
And now for the view(s):
// The view: Index.aspx
<!-- the non-AJAX form to filter the list -->
<% using (Html.BeginForm()) { %>
<fieldset>
<legend>Search</legend>
<input name="SearchTerm" />
<input type="submit" value="Go" />
</fieldset>
<% } %>
<!-- the AJAX form to filter the list -->
<script src="/Scripts/MicrosoftAjax.js" type="text/javascript"></script>
<script src="/Scripts/MicrosoftMvcAjax.js" type="text/javascript"></script>
<% using (Ajax.BeginForm("Index2", new AjaxOptions { UpdateTargetId = "results" })) { %>
<fieldset>
<legend>Search</legend>
<input name="SearchTerm" />
<input type="submit" value="Go" />
</fieldset>
<% } %>
<!-- render the partial inside the view -->
<div id="results">
<% Html.RenderPartial("Search", Model); %>
</div>
// The partial: Search.ascx (a default LIST T4 template, nothing special/custom)
2 comments:
on your example div id="results" is out of form , why is that can please explain ?
Because it's javascript, not a postback. MVC doesn't have postback or callback or update panels. They handle AJAX the old fashioned way, they script it.
Post a Comment