Navigate to my action/controller/id from jQuery - asp.net-mvc

I would like to navigate to my action/controller/id not from an ActionLink but from jQuery. Here is what I do:
$('.search-results tr').click(function () {
var IdSuite = $(this).data('idsuite');
var IdAffaire = $(this).data('idaffaire');
var url = '#Html.Raw(Url.Action("Detail","Suite", new { IdAffaire = "idAffaire", IdSuite = "idSuite" }))';
url = url.replace("idSuite", IdSuite);
url = url.replace("idAffaire", IdAffaire);
window.location = url;
});
I know it works but I would like to know if this is the best way to achieve this?
Thanks.

You don't need jQuery to do this.
If you want the user to be able to go back to the previous page after redirecting him, then using window.location = url is fine, otherwise you can use window.location.replace = url

Related

Still having ddl redirect issues

I am still having issues. I think what I am trying to do is simple. I have a viewbag droplist - which is working fine. I just want to redirect on selection it redirect just like: #Html.ActionLink("Branch", "Employees", new { Branch = item.Branch }) | (but with the selection from the droplist) Should this be difficult?
#Html.DropDownList("Branches", ViewBag.Branches as SelectList, "Select a Branch", new { #id = "ddlBranch" })
<script>
$(function () {
$("#ddlBranch").on("change", function () {
var deptId = $(this).val();
var routeVal = { Id: deptId };
var url = '#Url.Action("Department", "Home")';
$.ajax({
url: url,
type: 'POST',
data: routeVal
}).done(function (result) {
window.location.href = result.newUrl;
})
})
})
</script>
From a comment on the question above:
So now I just need to redirect to: #Html.ActionLink("Branch", "Employees", new { Branch = item.Branch }) but Item.Branch would be $(this).val(). Can this be done?
There may be a more elegant way, but an approach I've always taken is something like this:
let url = '#Html.ActionLink("Branch", "Employees", new { Branch = "REPLACEME" })';
url = url.replace('REPLACEME', $(this).val());
window.location.href = url;
On the client-side this turns into something like:
let url = '/Brand/Employees?Branch=REPLACEME';
url = url.replace('REPLACEME', encodeURIComponent($(this).val()));
window.location.href = url;
Which would look silly to anybody examining only the client-side code, I'm sure. But since the Branch parameter might be in the query string or might be in the route, and since it's the ASP.NET MVC Framework's responsibility to manage that, generating the URL and putting the client-side value into the URL are two separate responsibilities here.
So we use the server-side code to generate the URL with a placeholder (can be any string, "REPLACEME" was an arbitrary choice) and then use the client-side code to dynamically replace that placeholder with the desired value.
This essentially replaces whatever you're trying to do with AJAX in the original question. Unless you need to invoke a server-side operation to get a result not known to the client-side code in order to build the URL, you can just omit the AJAX entirely and build the URL directly.

firefox addon-sdk, display current page URL through Content Scripts

I recently started learning firefox addon development using Addon-SDK.
I created a simple addon which displays the current webpages URL, but I'm not getting the results.
Here's my main.js file
var widgets = require("sdk/widget");
var tabs = require("sdk/tabs");
var data = require("sdk/self").data;
var showipWidget = widgets.Widget({
id : "show-ip",
label : "Display IP Address of current Page",
contentURL : data.url("lens_icon.png"),
contentScriptURL : data.url("click_handler.js"),
/*onClick : function() {
var curtab = tabs.activeTab;
console.log(curtab.url+" is Opened in Browser.");
}*/
});
And The ContentScript click_handler.js
document.write(document.URL);
However when I use onClick event (commented code above) the URL is logged in console.
I think I'm accessing document object in wrong way. Can anyone show me how to do it right way.
That's weird that should work.
But try putting this in your content script:
var check = self.port.on("check", function() {
var location = window.location.href;
alert(location + " is opened in browser");
}
then emit that check function.
Figured out my problem. It was a silly mistake, I used contentScriptURL which is wrong. The correct term is contentScriptFile. I mixed content and contentURL with contentScript.
Reference from firefox:
http://tinypic.com/r/34447mc/8

How to add campaign tracking data to any url automatically?

I get a bunch of different URL from my sources and what I would like is to redirect to the same URL, but with campaign data added to URL (to track the referred clicks).
For example I have these URLs:
www.example.com/category/product/name.html
www.example.com/id_product=5
I want to add at the end the following: utm_source=SOURCE&utm_medium=MEDIUM&utm_campaign=CAMPAIGN
And the URLs to become
www.example.com/category/product/name.html?utm_source=SOURCE&utm_medium=MEDIUM&utm_campaign=CAMPAIGN
www.example.com/id_product=5&utm_source=SOURCE&utm_medium=MEDIUM&utm_campaign=CAMPAIGN
How to I correctly check and cover all the cases if a URL string has parameters, and add mine?
I want to do it in node.js
Thank you
Elaborating on #snkashis, a similar but arguably more elegant solution, again using node's url module, is:
var addQueryParams = function (cleanUrl) {
var obj = url.parse(cleanUrl, true, false);
obj.query['utm_source'] = 'SOURCE';
obj.query['utm_medium'] = 'MEDIUM';
obj.query['utm_campaign'] = 'CAMPAIGN';
delete obj.search; // this makes format compose the search string out of the query object
var trackedUrl = url.format(obj);
return trackedUrl;
};
This works, because url.format first looks for search and, if it can't find it, it composes the query string from the query object
(taken from node url module documentation http://nodejs.org/api/url.html#url_url_format_urlobj )
search will be used in place of query
query (object; see querystring) will only be used if search is absent.
Here is a example showing different scenarios using Node's URL module.
var url = require('url');
var exurls = ["www.example.com/category/product/name.html","www.example.com/id_product=5?hasparam=yes"]
var to_append = "utm_source=SOURCE&utm_medium=MEDIUM&utm_campaign=CAMPAIGN";
for (i=0;i<exurls.length;i++) {
var parsedobj = url.parse(exurls[i],true,false);
//Below checks if param obj is empty.
if (Object.keys(parsedobj.query).length!==0) {
var newpath = parsedobj.href+"&"+to_append;
}
else {
var newpath = parsedobj.href+"?"+to_append;
}
console.log(newpath);
}
Connect will help you:
var connect = require('connect');
var app = connect();
app.use(connect.query());
app.use(function (req, res, next) {
console.log(req.query);
res.end(JSON.stringify(req.query));
});
app.listen(3000);

jquerymobile and AJAX

seems to me that I didn't fully understand the concept behind jquerymobile, because I have no idea how to solve this issue.
What I want to do is load some HTML Content via AJAX, according to location.hash, put it into a new page and load this page.
But if I create a page myself by using the pagebeforechange event, jquerymobile just ignores it, creates its own div and my content won't be displayed.
How do I have to do it?
Edit:
This is how I am currently doing it, but it wont't work.
$(function() {
getPageContent(top.location.href, false);
$(document).bind( "pagebeforechange", function( e, data ) {
getPageContent(data.toPage, true);
});
});
function getPageContent(pageUrl, changedPage) {
var re = /.*\/#(.*)/;
var result;
result = re.exec(pageUrl);
window.page = result[1].substr(0,3);
window.id = result[1].substr(3);
window.ajaxUrl = "request.php?page="+window.page+"&id="+window.id;
$.ajax({
url: window.ajaxUrl,
success: function(data) {
if(data.error) {
alert(data.error);
}
else if(data.data) {
if(changedPage) {
changePage(data.data));
}
else {
$('#content[role="main"]').html(atob(data.data));
setupPage();
}
}
else {
alert("UNKNOWN ERROR: "+data);
}
}
});
}
function changePage(html) {
var div = "<div></div>";
var newPage = $(div).attr("data-role", "page").attr("data-url", window.page+window.id);
var header = $(div).attr("data-role", "header");
var content = $(div).attr("data-role", "content");
var footer = $(div).attr("data-role", "footer");
$("body").append(newPage);
newPage.append(header, content, footer);
content.html(html);
newPage.page();
}
Complete edit of the whole answer:
First. Set your body id to id=body. Then when you want to load the new page and change to it, use an ajax call like this:
$.get(window.ajaxUrl, function(data){
$('#body').append("<div id='newPage' data-role='page'></div>"); //Creates a new page.
$('#newPage').html(data); //Loads the html content into the new page.
$.mobile.changePage('#newPage'); //Navigates to the new page.
}
This sends an ajax call with the method GET to the url found in your window.ajaxUrl. If the call is successful, it creates a new page named "newPage", and fills it with the data received from the ajax call. Then redirects to the newly created page.
This jsFiddle shows the basics of how it works. However, it doesn't use any ajax call.
You have to refresh the page with jQueryMobile :
$("#your-page").trigger("create");
--Edit
<script>
$("#thepage").live("pageshow", function(){
$("#thepage).trigger("create");
});
</script>
Change the content of #thepage before 'pageshow' event
It does this for you automatically - just make a regular link to the page and jquery mobile will shwo the loading spinner, load it in the background via ajax, then transition to the new page.
Make sure all your pages are decide with unique IDs and data-role='page'. Check out the start guide here:
http://jquerymobile.com/demos/1.1.0/docs/about/getting-started.html

Url.Action is throwing error CS1026: ) expected

This is hopefully just a syntax error as I'm new to MVC and trying to edit something that already exists without having much experience. Having spent ages trying different syntax I'm obviously missing something.
My issue is that I have this:
var url = '<%= Url.Action("List") %>?page=' + pageNo;
which is fine, but its not passing in all the required parameters as part of pager functionality.
What I want to use is something like:
var url = '<%= Html.RenderAction("List",
"PlacementAgreementAgencyPlacementAgreementsPlacement",
new { Domain = "Placement",
Id = Model.Item.PlacementAgreement.PlacementAgreementId,
agencyPlacementAgreementId = Model.Item.AgencyPlacementAgreementId,
Page = Model.PageNo
});
%>';
But it always complains about error CS1026: ) expected
Same with trying
<%= Url.Action("List", "PlacementAgreementAgencyPlacementAgreementsPlacement",
new { Domain = "Placement",
Id = ViewData.Model.AgencyPlacementAgreement.PlacementAgreement.PlacementAgreementId,
agencyPlacementAgreementId = ViewData.Model.AgencyPlacementAgreement.AgencyPlacementAgreementId,
Page = Model.PageNo }
)%>
If someone could point out what I'm doing wrong that would be great. Basically I'm trying to call controller PlacementAgreementAgencyPlacementAgreementsPlacement with action List passing in all parameters Id, agencyPlacementAgreementId and Page. It's being done in javascript so that I can use this:
function loadAgreementPlacementPage(pageNo) {
var url = '<%= Url.Action("List") %>?page=' + pageNo;
$.get(url, function(data) {
$("#agreementplacement_list_holder").html(data);
});
Thanks!!!
PS. Using MVC 1.0.
It should be:
var url = '<%= Url.Action(
"List",
"PlacementAgreementAgencyPlacementAgreementsPlacement",
new {
Domain = "Placement",
Id = Model.Item.PlacementAgreement.PlacementAgreementId,
agencyPlacementAgreementId = Model.Item.AgencyPlacementAgreementId,
Page = Model.PageNo
}) %>';
Use Url.Action instead of Html.RenderAction and remove the semicolon at the end.
Remove the semicolon before the closing tag

Resources