Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing Javascript variable to route value in MVC3

I would like to pass a javascript variable in a @Url.Action method as a route parameter.

I like to pass the screenmode javascript variable as a route parameter to my action method.

I have a view model with ScreenMode enum property and based on it i should call a action in Ajax. I also need to pass a javascript variable as a parameter for route.

This is what i tried and got compilation error.

The name 'screenMode' does not exist in the current context

  $("#role-detail-form").submit(function (e) {

    if ($(this).valid()) {
    var screenMode = 0;
    @{
     if (Model.ScreenMode == UI.ViewModel.ScreenMode.New)
     {
       <text> 
       screenMode =2; 
       </text>
     }
    }
    $.post('@Url.Action("SaveRoleDetail", new { mode=screenMode})', 
            $(this).serialize(), function (data) {
                $("#role-detail").html(data);
                $.validator.unobtrusive.parse($("#role-detail"));
            });
        }
        e.preventDefault();
    });

My Action is

 public ActionResult SaveRoleDetail(RoleModel viewModel, ScreenMode screenMode)
    {
    }
like image 960
Murali Murugesan Avatar asked Jan 09 '13 10:01

Murali Murugesan


2 Answers

You'd have to split that out and build the query string yourself, in order to incorporate the Javascript variable.

Something like this is what you need:

$.post('@(Url.Action("SaveRoleDetail"))?screenMode=' + screenMode)

EDIT: Although probably best practice, you should store the ScreenMode variable in your Model, then put a HiddenFor in your view for it. Then, whenever you change the value in Javascript, simply update the value of the hidden input, that way your action method only needs to take the view model as a parameter. If you are posting the form in JavaScript and you can call $("#form").serialize() to send all the data back within your post call.

like image 78
mattytommo Avatar answered Oct 23 '22 18:10

mattytommo


Also it's possible to create a place holder and then replace it:

var url = '@Url.Action("GetOrderDetails", "Home", new { id = "js-id" })'
          .replace("js-id", encodeURIComponent(rowId)); 
like image 36
VahidN Avatar answered Oct 23 '22 17:10

VahidN