Passing dynamic javascript values using Url.action()
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
.
Passing url parameters from Url.Action variables in javascript
You usage of Url.Action()
in the script is generating &
instead of &
in the url, so instead of
../Controller/Action?candidacyId=cId&candidateId=cnId&typeOfAction=tpA"
you need to generate
../Controller/Action?candidacyId=cId&candidateId=cnId&typeOfAction=tpA"
You can do this by wrapping it in Html.Raw()
so its not encoded
addCandidateTaskUrl: "@Html.Raw(Url.Action("Action", "Controller", new { candidacyId = "cId", candidateId = "cndId", typeOfAction = "tpA" }))"
However, you can make this simpler and more efficient (without the need for multiple .replace()
) by just generating the base url, and the appending the query string parameters using the $.param method
view.params = {
baseUrl: '@Url.Action("Action", "Controller")' // Html.Raw not required
and
var queryString = $.param({ param1Id: actualParam1Id, param2Id: actualParam2Id, ... });
var uri = params.baseUrl + '?' + queryString;
How to access javascript variable within @URL.Action()
You can't. JavaScript doesn't execute when generating the action URL. What you can do, is do something like this:
function name(myjavascriptID) {
var link = '@Url.Action("download file", "download", new { id = "-1" })';
link = link.replace("-1", myjavascriptID);
jQuery("#list_d").jqGrid('setGridParam', { url: link, page: 1 });
}
Pass a javascript variable as parameter to @url.Action()
You need to build you url using javascript/jquery. In the view change the link to
<a id="export" href=#">Export as CSV</a>
Then in the script
var baseurl = '@Url.Action("Export")';
$('#export').click(function() {
var url = baseurl + '?SelectedAccountType=' + $('#SelectedAccountType').val() + '&FromDate=' + $('#FromDate').val() + '&ToDate=' + $('#ToDate').val() + ...etc
location.href=url;
});
However if your form is marked with FormMethod.Get
, then you can just use a normal submit button and no jquery is required
@using (Html.BeginForm("Export", "yourControllerName", FormMethod.Get))
{
@Html.TextBoxForm(m => m.SelectedAccountType)
....
<input type="submit" value="Export" />
}
How to pass dynamic value in @Url.Action?
I have functions to fetch invoking action and controller names, but
not sure how I can pass them in @Url.Action
Well, you could call those functions. For example if they are extension methods to the UrlHelper class:
window.location = '@Url.Action(Url.MyFunction1(), Url.MyFunction2())'
or if they are just static functions:
window.location = '@Url.Action(SomeClass.MyFunction1(), SomeClass.MyFunction2())'
If on the other hand the values that need to be passed are known only on the client you could do the following:
var param = 'some dynamic value known on the client';
var url = '@Url.Action("SomeAction", "SomeController", new { someParam = "__param__" })';
window.location.href = url.replace('__param__', encodeURIComponent(param));
UPDATE:
It seems that you are just trying to fetch the current controller and action which could be achieved like that:
@{
string currentAction = Html.ViewContext.RouteData.GetRequiredString("action");
string currentController = Html.ViewContext.RouteData.GetRequiredString("controller");
}
and then:
window.location.href = '@Url.Action(currentAction, currentController)';
pass variable as parameter to Url.Action in javascript
I solved it by using this:
function showHistory()
{
myId= $("#id").val();
actionDialog.load("@Url.Action("ActionHistoryAjax", new {id = "_Id", sort = "abc"})".replace("_Id", DeviceID), function () {
actionDialog.dialog('open');
});
}
ASP.Net MVC: How could i pass js array to mvc action by @Url.Action()
Click on this fiddle https://dotnetfiddle.net/RRwK1K
View
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Tut123</title>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script type="text/javascript">
$(function () {
$("#theButton").click(function () {
var id = "10";
var deptno = "C001";
var PdfInputs = [];
var i;
for (i = 0; i <= 3; i++) {
PdfInputs.push({
firstName: "John",
lastName: "Doe",
age: 46
});
}
var json = JSON.stringify(PdfInputs);
location.href = '@Url.Action("theActionPassArray", "Home")?json=' + json;
})
})
</script>
</head>
<body>
<input type="button" id="theButton" value="Go" />
@*credit to https://stackoverflow.com/questions/15112055/passing-dynamic-javascript-values-using-url-action*@
@if (ViewBag.Data != null)
{
<span>The data sent to the server was:</span>@ViewBag.Data
}
</body>
</html>
Controller
public class PassArray
{
public string firstName { get; set; }
public string lasttName { get; set; }
public string age { get; set; }
}
public class HomeController : Controller
{
public ActionResult theActionPassArray(string json)
{
/turn json passed value into array
//You need to get NewtonSoft.JSON
PassArray[] arr = JsonConvert.DeserializeObject<PassArray[]>(json);
//put breakpoint here
ViewBag.Data = json;
return View("Tut123"); }
public ActionResult Tut123()
{
return View();
}
Dynamic Redirect from Url.Action
Since you're doing an ajax request, your Action should return the Id of the created object, and you should handle the redirection via JS.
So change the return type and value of your Action to:
public ActionResult CreateObj(string value) {
int id = newObj.objectId;
return Json(id, JsonRequestBehavior.AllowGet);
}
And register a callback function on your post() method to perform the redirection:
$.post("@Url.Action("CreateObj", "Object")", {
value:"value"
}).done(function (data) { // data represents the returned id
//handle success
window.location.href = `@Url.Action("Edit", "Object")/${data}`;
}).fail(function () {
//Handle failure
})
• Check how $.post() works on jQuery.post().
Related Topics
How to Access External Json File Objects in Vue.Js App
React Router Not Working After the Page Refresh
How to Select All Textframes in Document, and Retrieve the Text in Adobe Indesign
How to Prevent User to Enter Specific Key Using JavaScript
Filter Array of Dates Between Two Dates
Regex to Allow Only Certain Special Characters and Restrict Underscore
How to Restrict Past Dates in Html5 Input Type Date
Loading Screen Gets Stuck While Processing Http Request
Disable/Hide Download Button in Iframe on Default Pdf Viewer
How to Refresh Form Page After Post Request
Opening Pdf String in New Window With JavaScript
How to Replace Double/Multiple Slash to Single in Url
How to Clear Input After Onclick With Reactjs
How to Execute a Function After Another One