什么是在MVC2中读取/传递查询字符串值到视图的正确方法?

时间:2010-07-15 04:49:36

标签: asp.net-mvc-2

我的网址工作正常,因为我可以进入控件正确的方法但是..我是如何从网址中读取状态名称到视图中?

我的网址:http://localhost:10860/Listings/Arizona/page1

我的观点:

>“%>

<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>.....

2 个答案:

答案 0 :(得分:0)

我会避免在你的视图中有那么多代码。为什么不使用控制器读取Querystring并使用ViewData将值传递给控制器​​。

控制器

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

标记

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

答案 1 :(得分:0)

以下位不属于视图

<%
 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();
%>

其中一些应该真的应该在控制器动作方法中。

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);
 }
}

操作方法中的参数state将来自URL。根据您设置路线的方式,它可能是mysite.com/home/NY或mysite.com/home/?state=NY

然后在视图中:

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