Home > database >  Passing value from view to controller using location.href is null
Passing value from view to controller using location.href is null

Time:11-18

I have a view, in which I have a dropdown onchange event. I want to pass the selected value from the dropdown to the controller using location.href, but I can't manage to successfully do it.

I added in the alert to help me see what the value is, which correctly displays the selected value from the drop-down.

My view:

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

My controller:

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

This results in groupName being "groupName" in the controller parameters.

I also tried

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

But that passes null to the controller.

What is the correct way/syntax to do this? Any help is greatly appreciated!

CodePudding user response:

You can try this way:

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

CodePudding user response:

You could use Ajax request for this call. Here you have an example how to implement it :

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

CodePudding user response:

change routes configuration

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