开发者

What's the Proper way to read/pass querystring values to a view in MVC2?

my url is working correctly as i can step into the controls correct method but..how am I to read the state name from the url into the view?

My url: http://localhost:10860/Listings/Arizona/page1

My view:

>" %>

<h2>Test BY STATE</h2>

 <%
     LOTW.Models.ListingRepository dr = new LOTW.Models.ListingRepository();
     ListViewListings.DataSource = dr.GetByStateName(???? I can hard code "Arizona" and this works???????); // how do i grab the 'Arizona' from the url? Reqquest.Querystring doesn't work?
     ListViewListings.DataBind()开发者_运维问答;
    %>

 <%--Define the table headers to work with the tablesorter--%>
    <asp:ListView runat="server" ID="ListViewListings">
        <LayoutTemplate>
            <table id="ListViewListings" class="tablesorter">
                <thead>
                    <tr>.....


I would avoid having that much code in your View. Why not use your controller to read the Querystring and pass the value to the controller with ViewData.

Controller

Function Index() As ActionResult
   ''# however you access your repository
   ViewData("StateName") = dr.GetByStateName(Request.QueryString("TheState"))
End Function

Markup

<% For Each item In ViewData("StateName") %>
       <li><%: item.State %></li>
<% Next%>


The bit below does not really belong in the view

<%
 LOTW.Models.ListingRepository dr = new LOTW.Models.ListingRepository();
 ListViewListings.DataSource = dr.GetByStateName(???? I can hard code "Arizona" and this works???????); // how do i grab the 'Arizona' from the url? Reqquest.Querystring doesn't work?
 ListViewListings.DataBind();
%>

Some of it should really should be in the controller action method.

class HomeController {
 public ActionResult Index(string state) {
   LOTW.Models.ListingRepository dr = new LOTW.Models.ListingRepository();
   var list = dr.GetByStateName(state); // how do i grab the 'Arizona' from the url? Reqquest.Querystring doesn't work?

   return View(list);
 }
}

Parameter state in the action method will come from the URL. Depending on how you set up your routes, it would either be mysite.com/home/NY or mysite.com/home/?state=NY

Then in the view:

<%
 ListViewListings.DataSource = Model;
 ListViewListings.DataBind();
%>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜