Use JavaScript variable as route argument - javascript

I try to add $(this).prev("input").val() in my id argument for an API route, but I don't know how to stop the C# part , I thought about <text></text> or #: but doesn't work like this.
Anyone has a trick ? (thought about writting the URL instead of using the RouteURL function but I don't think it's a good way to program)
$.ajax({
url: '#Url.RouteUrl("IsTranslated", new { id = <text>$(this).prev("input").val()</text> }, new {market=#ViewBag.market })
// [...]
})

You can't inject a JavaScript value like that (remember, the Razor code is evaluated server-side). What you can do is use your helper to build a "template" string, and replace the id value:
var template = '#Url.RouteUrl("IsTranslated", new { id = 0 }, new { market=#ViewBag.market })';
var id = $(this).prev("input").val();
var url = template.replace('id=0', 'id='+id);
$.ajax({
url: url
// [...]
})
This assumes, of course, that a querystring value is generated by the helper. If not, this might work:
var template = '#Url.RouteUrl("IsTranslated", new {}, new { market=#ViewBag.market })';
var id = $(this).prev("input").val();
var url = template.replace('IsTranslated', 'IsTranslated?id='+id);
$.ajax({
url: url
// [...]
})

Related

Asp.Net MVC parameter is null when pass it from client side to controller

Javascript
I have a method as follows,
function OpenRecord(id ,module ,screen) {
var url = '#Url.Action("OpenRecord", "Management", new { id = "_id", module = "_module",screen = "_screen" })';
url = url.replace("_id", encodeURIComponent(id));
url = url.replace("_module", encodeURIComponent(module));
url = url.replace("_screen", encodeURIComponent(screen));
window.location.href = url;
}
Controller
public ActionResult OpenRecord(string id, string module, string screen)
{
Int64 someID = Convert.ToInt64(id);
/*some act**/
return RedirectToAction(screen, module, new { id = someId});
}
When I run this i get id and module but screen param is passed null. When i inspect client side on chrome dev tools, i see all the parameters on javascript method are filled and the final url in url variable as follows;
/Management/OpenRecord/112?module=Customer&screen=MUSTRTANML
I guess that amp&; entity spoils my controller to get the last param but i am not sure and i don't know how to solve this.
Thanks in advance.
Simply wrap your Url.Action in Html.Raw(). Or you can go with replacement approach further - url = url.replace("&", "&"). Whatever you like, personally I would proceed with Html.Raw
you need to construct your url string with values
var url = '#Url.Action("OpenRecord", "Management", new { id = "_id", module = "_module",screen = "_screen" })';
this is wrong, it should be
var url = '/Management/OpenRecord?id=' + _id + '&module='+ _module + '&screen='+ _screen;
the above will pass the values of the variables rather than names , you cannot execute Url.Action as part of JavaScript this is Razor code

How to insert javascript var into path on Twig?

I want to insert a var declared in javascript into my path to redirect my page.
My code is:
var id = $(this).attr('data-id');
windows.location = {{ path("mylink", {id: id}) }};
But I can't know how can insert my var id into path, because when I try this I get error, I'm trying to parse this with +' myvar '+ so concatenating text but I can't.
How can I concatenate or add my var into path?
Thanks!
Because PHP is executed on server side, you need to bypass by this way:
var id = $(this).attr('data-id');
var path = {{ path("mylink", {id: 0420}) }};
windows.location = path.replace("0420", id);
There is a way to do this without having to use javascript replace function. However, it requires some work.
Create Twig extension to decode URL:
namespace AppBundle\Twig\Extension;
class UrlDecodeExtension extends \Twig_Extension
{
public function getFilters()
{
return array(
new \Twig_SimpleFilter('url_decode', array($this, 'UrlDecodeFilter'))
);
}
public function UrlDecodeFilter($url)
{
return urldecode($url);
}
public function getName()
{
return 'url_decode_extension';
}
}
Register your new extension:
url_decode_extension:
class: AppBundle\Twig\Extension\UrlDecodeExtension
tags:
- { name: twig.extension }
Finally, use it in your Twig template:
var id = $(this).attr('data-id');
windows.location = {{ path("mylink", {id: "%s"}) | url_decode | format('"+id+"') | raw }};
This is how it is going to render in the browser:
var id = $(this).attr('data-id');
window.location("/your/rendered/url/"+id+"");
You should really consider using FOSJsRoutingBundle. It is one of the most commonly used bundles. Its only purpose is to expose the routes you want to client side. Once installed, your code would be :
var id = $(this).attr('data-id');
windows.location = Routing.generate("mylink", {id: id});

How to pass the value to URL from dropdown item?

I am asking this question again....because I am not getting correct answer...
answers which I get is incorrect.
I am developing MVC application and I am using razor syntax. I am trying to get the selected item from dropdown list value and to pass it to the controller method.
but I am getting error.
$("#btnForword").click(function(){
d = document.getElementById("HODList").value;
var url2 = "#Html.Raw(Url.Action("SendPaymentAdviceForApproval", "PaymentAdvice", new { paymentAdviceId = "idValue" , nHOD = "d" }))";
url2 = url2.replace("idValue",'#Model.Id');
url2 = url2.replace("d",'#d');
$.ajax({
url: url2, type: "POST", success: function (data) {
$("#btnForword").css("display","none");
}
});
return false;
});
I think error in this line...
url2 = url2.replace("d",'#d');
Issue solved Issue solved
The problem in variable 'D' yes in "D".
I checked using inspect element property of Google chrome, when I saw it in console window....
When I click on the button , I can see the string formed in below way
http://localhost:54255/PaymentAdvice/SendPaymentAdviceForApproval?paymentAdviceId=304&nHO8=D
jquery-1.7.1.min.js:4
see the last character in the above link, it should not be come as a "=D" isnt it ?
I used the below code...and it works perfectly.
$("#btnForword").click(function(){
var url2 = "#Html.Raw(Url.Action("SendPaymentAdviceForApproval", "PaymentAdvice", new { paymentAdviceId = "idValue" , nHOD = "HODId" }))";
url2 = url2.replace("idValue",'#Model.Id');
url2 = url2.replace("HODId",$('#HODList').val());
$.ajax({
url: url2, type: "POST", success: function (data) {
$("#btnForword").css("display","none");
}
});
return false;
});
Is this a bug in Jquery ?
Your variable d is not a server variable that can be called with "#" but a client variable set in javascript, so it should be user like :
$("#btnForword").click(function(){
d = document.getElementById("HODList").value;
var url2 = "#Html.Raw(Url.Action("SendPaymentAdviceForApproval", "PaymentAdvice", new { paymentAdviceId = Model.Id , nHOD = "d" }))";
url2 = url2.replace("d",d);
$.ajax({
url: url2, type: "POST", success: function (data) {
$("#btnForword").css("display","none");
}
});
return false;
});
(and the "#Model.Id" can be called directly in the Url.Action method).
Yes it is. The problem is that the js replace function replaces every "d" character contained in the url2 string with your #d variable!!!
You need to replace the "d" identifier with something that does not appear twice (or more) in the url string. Besides, I think is better if you create the url directly using javascript and not the Razor helper. You can do this in one line of code instead of three. Regards.

Setting asp.net MVC4 web api route url in javascript is returning empty string

Here is the code that I am using to set the api url:
var clientUrl = '#Url.RouteUrl("ApiControllerAction", new { httproute="", controller = "Client"})';
In my route.config the route looks like this:
routes.MapHttpRoute(
name: "ApiControllerAction",
routeTemplate: "api/{controller}/{action}/{id}"
);
And the action on my controller that I am trying to hit is this:
[ActionName("clients")]
public IQueryable<Client> GetClients(int id)
{
return Uow.Clients.GetClients(id);
}
I have a function in javascript that is trying to hit this api, but I am getting a 404:
var getClients = function (id) {
return $.ajax(clientUrl + "/clients/" + id)
};
When I call getClients(1) the url is trying to hit is this:
localhost:12345/clients/1
Rather than my expected url of this:
localhost:12345/api/client/clients/1
Any idea where this is going wrong? I had this working in another project and can't remember if there is something else I am supposed to do. If I inspect the javascript the clientUrl = ''.
I came across this answer How to create ASP.NET Web API Url? which helped.
Example code for my answer here on GitHub
You can alter your #Url.RouteUrl code to include both the action name and the "ID" which currently appears not to be optional for your action route... this is probably why it is failing to find a match and returning an empty string. So try:
var clientUrl = '#Url.RouteUrl("ApiControllerAction", new { httproute="", controller = "Client", action = "clients" id=#... })';
NB. id=#... })'; at the end ... being what ever the id is going to be var or property on a model etc...
Or
You could of course just make ID optional which will also work:
config.Routes.MapHttpRoute(
name: "ApiControllerAction",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
Or
You may find it cleaner to avoid using an action... clients could live in its own controller ClientsController and you can use the routes and defaults to route to it:
routes.MapHttpRoute(
name: "ApiControllerAction",
routeTemplate: "api/client/clients/{id}",
defaults: new { controller="Clients" }
);
Then this should give you the required response:
var clientUrl = '#Url.RouteUrl("ApiControllerAction", new { httproute="", controller = "Clients" })';
//api/client/clients/
and...
var clientUrl = '#Url.RouteUrl("ApiControllerAction", new { httproute="", controller = "Clients", id=#... })';
//api/client/clients/x
Try to set the clientUrl like this:
var clientUrl = '#Url.RouteUrl("ApiControllerAction", new { httproute="", controller = "Client", action = "clients"})';
And then in change getClients to this:
var getClients = function (id) {
return $.ajax(clientUrl + "/" + id)
};

Specifying a callback in jQuery.ajax to OpenCalais SemanticProxy service

I'm trying to query the OpenCalais service semanticproxy.com. Unfortunately, their url format is as follows:
http://service.semanticproxy.com/processurl/APIKEY/jsonp:handler_function/http://en.wikipedia.org/wiki/Germany
notice that the function callback, is not in a callback=? parameter, but rather follows the response format (jsonp:). This means that I can't use .getJSON, but rather need to use the .ajax method. So I have the following object definition:
function Subject() {
}
Subject.prototype.populate = function(page_title) {
var url = "http://service.semanticproxy.com/processurl/APIKEY/jsonp:handler/http://en.wikipedia.org/wiki/" + page_title;
$.ajax({url: url, dataType: "script", type: "GET", cache: false, callback: null, data: null});
};
var handler = function (data) {
// do stuff with the returned JSON
};
s = new Subject();
s.populate("Germany");
This works fine. But what I really want to do is set properties of my Subject object. But I don't know how to create a function in the context of the Subject that will be able to be used as the callback. i.e:
Subject.prototype.handler = function(data) { this.title = data.title }
Any ideas?
You'd have to set a function on the window object. This is essentially (I think) what jQuery does with its .getJSON method. The below is a bit hacky but hopefully it points you in the right direction:
function Subject() {
}
Subject.prototype.populate = function(page_title) {
// Save context object
var subject = this;
// Create function name like subjectHandler1281092055198
var functionName = "subjectHandler" + new Date().getTime();
window[functionName] = function(data) {
// Invoke function with saved context and parameter
subject.handler.call(subject, data);
}
var url = "http://service.semanticproxy.com/processurl/APIKEY/jsonp:" + functionName + "/http://en.wikipedia.org/wiki/" + page_title;
$.ajax({url: url, dataType: "script", type: "GET", cache: false, callback: null, data: null});
};
Subject.prototype.handler = function (data) {
// do stuff with the returned JSON
};
s = new Subject();
s.populate("Germany");
I don't think you're going to be able to do this, just because of how JSONP works, look at how it actually comes back to the browser, it pretty much does this:
<script type="text/javascript">
handler({ title: "Germany", ...other properties... });
</script>
There's no way to maintain a reference here, you could do one request at a time, or keep an object map for each subject, but there's no way to do it in the JSONP request.
An object map would look something like this:
//delcare this once for the page
var subjects = {};
//do this per subject
var s = new Subject();
s.populate("Germany");
subjects["Germany"] = s;
Then in your hanldler, if any of the data properties is "Germany", you could get it that way, for example:
var handler = function (data) {
var subject = subjects[data.title];
//subject is your Germany subject, use it, go nuts!
};

Categories

Resources