【问题标题】:Passing value from view to controller using location.href is null使用 location.href 将值从视图传递到控制器为 null
【发布时间】:2021-12-28 15:19:19
【问题描述】:

我有一个视图,其中有一个下拉列表onchange 事件。我想使用location.href 将下拉列表中的选定值传递给控制器​​,但我无法成功地做到这一点。

我在alert 中添加了帮助我查看值是什么,它正确显示了从下拉列表中选择的值。

我的看法:

<div class="modelDropdown">
    @Html.DropDownListFor(m => m.groupId, Model.pointGroupDropdown, "Select a Model", new { @id = "pointGroupDropdown", @onchange = "LoadPointGroups(this)", @class = "form-control", @style = "width: 200px;" })
</div>

<script>
    function LoadPointGroups(pointGroup) {
        alert(pointGroup.options[pointGroup.selectedIndex].text);
        var groupName = pointGroup.options[pointGroup.selectedIndex].text;
        location.href = '@Url.Action("LoadPointGroups", new {groupName = "groupName"})';
    }
</script>

我的控制器:

public ActionResult LoadPointGroups(string groupName){
    *do stuff*
}

这导致groupName 在控制器参数中成为“groupName”。

我也试过

location.href = '@Url.Action("LoadPointGroups")/' + groupName;

但这会将null 传递给控制器​​。

执行此操作的正确方法/语法是什么?非常感谢任何帮助!

【问题讨论】:

    标签: javascript c# asp.net-mvc-5


    【解决方案1】:

    您可以为此调用使用 Ajax 请求。这里有一个如何实现它的示例:

    var BaseUrl = '@Url.Content("~/")';
    
    function LoadPointGroups(pointGroup) {
            var groupName = pointGroup.options[pointGroup.selectedIndex].text;  
    
     $.ajax({
                  BaseUrl + yourControllerPath + '/LoadPointGroups?groupName=' + groupName,
                  method: 'GET',  //Your controller's method type
                  cache: false,
                }).done(function (whatYouGet) {
                    // You could also do sth here if it's a get method
           }); 
       }
    

    【讨论】:

      【解决方案2】:

      你可以试试这个方法:

      function LoadPointGroups(pointGroup){
         alert(pointGroup.options[pointGroup.selectedIndex].text);
         var url =@Url.Action("YourMethodName", "ControllerName"); //your url
         var gName = pointGroup.options[pointGroup.selectedIndex].text; //your value
         window.location.href = url + "?groupName=" + gName;
       }
      

      【讨论】:

        【解决方案3】:

        更改路由配置

        routes.MapRoute(
                        name: "Default",
                        url: "{controller}/{action}/{id}",
                        defaults: new { controller = "Help", action = "Index", id = UrlParameter.Optional }
                    ).DataTokens = new RouteValueDictionary(new { area = "HelpPage" });
        

        【讨论】:

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