【问题标题】:Routelink viewdata value is always nullRoutelink viewdata 值始终为空
【发布时间】:2010-12-09 18:23:12
【问题描述】:

我有一个路由规则

 routes.MapRoute(
            "Search",                                                     // Route name
            "Restaurant/AdvancedSearch/{foodType}",                       // URL with parameters
            new { controller = "Restaurant", action = "AdvancedSearch", foodType = "" }  // Parameter defaults
        );

在我看来,我想将值从选择列表传递到 routeLink

<% using (Html.BeginForm("SimpleSearch", "Restaurant")) { %>
    <div>
        <fieldset>
            <legend>Restaurant Search</legend>
            <label for="Food">Type of food:</label>
            <%= Html.DropDownList("Food", Model.FoodType, "-- Select --")%>

            <%= Html.RouteLink("Advanced search?", "Search", new { foodType=(ViewData["Food"]) })%>
      </fieldset>
    </div>
<% } %>

在我的控制器中,foodType 值始终为 null,而不是所选值的项目 id?

public ActionResult AdvancedSearch(int? foodType)
    {
        return View();
    }

【问题讨论】:

    标签: asp.net-mvc asp.net-mvc-routing


    【解决方案1】:

    没有看到你的模型类,很难知道。但我认为你想这样做:

    <%= Html.DropDownList("Food", ViewData["Food"], "-- Select --")%>
    <%= Html.RouteLink("Advanced search?", "Search",new {foodType= Model.FoodType})%>
    

    假设ViewData["Food"] 包含IEnumerable&lt;Seleclist&gt; 并且Model.FootType 返回模型食物类型的ID。

    【讨论】:

      【解决方案2】:

      您的 RouteLink 是在服务器端构建的,这意味着它将始终是静态的 - foodType 将始终等于 ViewData["Food"] 的值。当用户更改下拉列表中的选择时,您需要使用 javascript 使用新值修改链接。以下是实现此目的的方法:

      $(function() {
          $('select#Food').change(function() {
              $('a').attr('href', '/Restaurant/AdvancedSearch/' + $(this).val());
          });
      });
      

      备注:此解决方案有一个缺点:如果您修改路由,它将不再起作用,因为 href 是在 javascript 中硬编码的。

      【讨论】:

        猜你喜欢
        • 2019-07-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-08-18
        • 1970-01-01
        • 1970-01-01
        • 2021-08-22
        • 2018-03-20
        相关资源
        最近更新 更多