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)
{
}
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.
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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With