【问题标题】:What's the Proper way to read/pass querystring values to a view in MVC2?将查询字符串值读取/传递到 MVC2 中的视图的正确方法是什么?
【发布时间】:2010-07-15 04:49:35
【问题描述】:

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

我的网址: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>.....

【问题讨论】:

    标签: asp.net-mvc-2


    【解决方案1】:

    我会避免在您的视图中包含那么多代码。为什么不使用您的控制器读取查询字符串并使用 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%>
    

    【讨论】:

    • 是的,我更喜欢你的想法......比我刚刚发现的让它起作用......而不是 request.querystring[....]......它是 RouteData.Values[" stateName"].ToString()...但我会把它放在控制器中...谢谢 x 10
    • 尽量不要在标记中使用&lt;asp: ... /&gt; 控件。相反,尝试接受 MVC 的真正无状态特性,并尽可能多地使用通用 HTML。我还没有找到任何理由在我的视图中使用DataSources&lt;asp: ... /&gt; 控件。
    【解决方案2】:

    下面的位并不真正属于视图

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

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

    然后在视图中:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多