Could anyone please tell how to pass dynamic values using Url.action().
Something Like,
var firstname="abc";
var username = "abcd";
location.href = '@Html.Raw(@Url.Action("Display", "Customer", new { uname = firstname ,name = username}))';
firstname, username is not getting reffered inside the Url.action() method.
How to pass these dynamic values using Url.action()?
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
The @Url.Action() method is proccess on the server-side, so you cannot pass a client-side value to this function as a parameter. You can concat the client-side variables with the server-side url generated by this method, which is a string on the output. Try something like this:
var firstname = "abc";
var username = "abcd";
location.href = '@Url.Action("Display", "Customer")?uname=' + firstname + '&name=' + username;
The @Url.Action("Display", "Customer") is processed on the server-side and the rest of the string is processed on the client-side, concatenating the result of the server-side method with the client-side.
Method 2
This answer might not be 100% relevant to the question. But it does address the problem.
I found this simple way of achieving this requirement. Code goes below:
<a href="@Url.Action(" rel="nofollow noreferrer noopener"Display", "Customer")?custId={{cust.Id}}"></a>
In the above example {{cust.Id}} is an AngularJS variable. However one can replace it with a JavaScript variable.
I haven’t tried passing multiple variables using this method but I’m hopeful that also can be appended to the Url if required.
Method 3
The easiest way is:
onClick= 'location.href="/controller/action/" rel="nofollow noreferrer noopener"+paramterValue'
Method 4
In my case it worked great just by doing the following:
The Controller:
[HttpPost]
public ActionResult DoSomething(int custNum)
{
// Some magic code here...
}
Create the form with no action:
<form id="frmSomething" method="post">
<div>
<!-- Some magic html here... -->
</div>
<button id="btnSubmit" type="submit">Submit</button>
</form>
var frmSomething= $("#frmSomething");
var btnSubmit= $("#btnSubmit");
var custNum = 100;
btnSubmit.click(function()
{
frmSomething.attr("action", "/Home/DoSomething?custNum=" + custNum);
btnSubmit.submit();
});
Hope this helps vatos!
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0