I want to redirect a another page using ajax call. I used below code but it doesn't redirect
def show_item_details
#itm_id=params[:Id]
redirect_to prd_item_path(#itm_id)
end
ajax code
$.ajax({
type:"GET",
url: url,
dataType:"json",
data: {PrdId: parseInt(prdId)},
success:function(result){
setItemDetails(result)
}
});
There are a lot of ways.
One option would be to pass the new location from the controller to the frontend and redirect with javascript.
success:function(result){
window.location.href = result;
}
Other option would be to avoid redirecting but rendering the new page and showing the html.
success:function(result){
$('body').html(result);
}
This is easy on javascript but all the work has to be done in the controller.
Hope this helps!
I am using the Kendo window right now and they have an ajax method meant to load in new content to the window. This works on my localhost but for some reasons stops when I publish the site to a remote server. The content is just never loaded in, I have debugged the javascript on the server and the ajax calls are being made. Any help would be appreciated.
This is the code I am using.
#(Html.Kendo().Window()
.Name("window")
.Title("test")
.Actions(Image => Image
.Custom("custom")
.Minimize()
.Maximize()
.Close()
)
//.LoadContentFrom(#Model.selectedModule, "Modules")
.Draggable()
.Resizable()
.Width(500)
.Modal(true)
.Height(500)
.Visible(false)
)
function test(link) {
var use = link.title;
var dialog = $("#window").data("kendoWindow");
dialog.refresh({
url: "/Modules/" + use
});
setTimeout("open()", 200);
};
function open() {
var dialog = $("#window").data("kendoWindow");
dialog.center();
dialog.open();
}
</Script>
In the end I took the suggestion and replaced the method with the URL helper. The codeblock is as follows.
function test(link) {
var use = link.data('url');
var dialog = $("#window").data("kendoWindow");
dialog.refresh({
url: use
});
setTimeout("open()", 200);
To me it sounds like the URL is not resolved when using the deploying envirment. Can you try and use the URL helper which MVC provides? Also you can use network tools of the browser to see what actually the server responded.
I've got a fairly simple question for all the Razor experts out there. I'm trying to make a jQuery $.ajax() call to a URL, using Url.Content() to translate the home-relative path into an root-relative path. In so doing, Razor is getting a bit confused about where the end of my #section is located. I'd prefer to be able to specify the URL inline, but when I do that, Razor thinks that the end of the $.ajax() parameter list is the end of my #section. I'm using #section because I want to use layouts to place my javascript at the bottom of each file. Why is Razor getting so confused? I've even tried using #(Url.Content(...)), but that doesn't work either.
Also, is this the best way to approach the problem? I'm using the ASP.NET MVC 4 Preview.
This works:
#section Scripts {
<script type="text/javascript">
var getMessagesUrl = '#Url.Content("~/Logging/GetMessages")';
$(document).ready(function () {
$.ajax({
url: getMessagesUrl,
dataType: 'html',
success: function (result) {
$('tbody').html(result);
}
});
});
</script>
}
This doesn't:
#section Scripts {
<script type="text/javascript">
$(document).ready(function () {
$.ajax({
url: '#Url.Content("~/Logging/GetMessages")',
dataType: 'html',
success: function (result) {
$('tbody').html(result);
}
}); //Razor thinks this is the curly-brace that ends the section!
});
</script>
}
This is likely down to the behaviour of the parser. When it encounters the # symbol, the parser switches to code mode and will read the implicit expression Url.Content("~/Logging.GetMessages") (well, actually it will read until the ' symbol, determine it is not a valid character in an expression and trackback to return until the end of the ). It's after this stage that the parser is getting a little confused with your view because it's likely in code mode when it encounters the final } character, and thinks it is the end of of a code span.
The reality is, you have to be quite careful when using javascript within a razor view with C#. The transitions to code are explicit, e.g. # and after a {, but the transitions to markup are a little harder to determine.
Razor aside, my recommendation would be to stick your javascript application code in an external file, and take advantage of data-* attributes to convey meta information to your application code, e.g:
<script id="messageScript" type="text/javascript"
src="/Scripts/messages.js"
data-messages="#Url.Content("~/Logging/GetMessages")"></script>
Which you can access as:
(function($) {
$(function() {
var $this = $("#messageScript");
$.ajax({
url: $this.attr("data-messages"),
type: "html",
success: function(result) {
$("tbody").html(result);
}
});
});
})(window.jQuery);
Update: Dave's less than symbol was not causing the problem, he only added it in his question for illustrative purposes.
On MVC4 I was able to isolate the issue. This would not compile:
<script type="text/javascript">
$(document).ready(function () {
$.ajax({
url: '#Url.Content("~/Logging/GetMessages")',
dataType: 'html',
success: function (result) {
$('tbody').html(result);
}
}); //<-- test
});
</script>
But this would:
<script type="text/javascript">
$(document).ready(function () {
$.ajax({
url: '#Url.Content("~/Logging/GetMessages")',
dataType: 'html',
success: function (result) {
$('tbody').html(result);
}
}); //-- test
});
</script>
Seems like it was just the < in the comment that was throwing it.
Matthew's answer pretty much explains the behaviour (although, to be honest, I can't reproduce your problem - nor see why it wouldn't work - both your examples run just fine here). For a different approach, you could dedicate an action/view to generated javascript variables (urls, settings, localized texts, whatever), i.e.:
// Could/should be OutputCached depending on the scenario
public ActionResult Globals()
{
var model = new ClientGlobalsModel();
// ClientGlobalsModel has a single (could be more) Dictionary<string, string>
// (Urls) and a ToJSON() method which uses JavaScriptSerializer to serialize
// the object:
model.Urls.Add("GetMessages", Url.Content("~/Logging/GetMessages"));
// I mostly use this method for e.g. actions:
model.Urls.Add("UploadImage", Url.Action("Upload", "Image"));
Response.ContentType = "text/javascript";
return View(model);
}
Globals.cshtml:
#model ClientGlobalsModel
#{
Layout = null; // If you have a layout supplied in e.g. _ViewStart
}
var GLOBALS = #Model.ToJSON()
Yeah, this could have been a simple Content() result rather than a view - but when you have more globals (e.g. settings + urls + texts), you may want easier control over the script output and maybe serialize each dictionary individually. May also want to namespace that "GLOBALS" variable in some shared application namespace to avoid polluting the global scope.
(e.g.) Index.cshtml:
<script src="#Url.Action("Globals", "Client")"></script>
<script src="#Url.Content("~/Scripts/main.js")"></script>
... which simply includes the output from /Client/Globals. And "main.js", into which we have now moved the rest of your script:
main.js (static):
$(document).ready(function () {
$.ajax({
url: GLOBALS.Urls.GetMessages,
dataType: 'html',
success: function (result) {
$('tbody').html(result);
}
});
});
You can, of course, use the same kind of approach to output a few user/context/view-specific settings directly into the view. For a few URL's or data, the data-* attribute approach may be better depending on your tastes. I'm not a fan of stuffing tons of what's basically settings into attributes on every HTML page, though.
Seems to still be a problem with final MVC4 / Visual Studio 2010, but here is my fix:
#section jQueryDocumentReady
{
#{
<text>
// All the javascript and bracers you want here
</text>
}
}
Thanks for all of the help, folks.
It looks like it must have been a bug in the ASP.NET MVC 4 Preview. I just upgraded to the ASP.NET MVC 4 Beta which came out on February 15, and the problem is now completely gone.
I have forms located in multiple areas in my layout page (not nested).
I have a partial view which performs a post to controller action.
What action result do I return in that post to keep the user on the current page?
Is jquery/ajax my only option? I would rather a solution that didn't depend on javascript, maybe even a solution that degrades nicely.
You can use the Request.Referrer property to see what page the user has come from and then just use that to redirect them back there.
This does introduce other issues, e.g. losing ModelState, so you'll have to design for that. Also note that some users can block sending referrer information in their requests to the server - so the Referrer property can be null.
I would recommend using AJAX and then falling back on this.
You just need to do a RedirectToAction("") back to your main view.
To post a form without submitting the whole page, which refreshes the browser, you need to use Ajax/jQuery. The degraded solution is to submit the whole page like you would with a normal form.
Here's how I do it with jQuery.
Html:
<div id="RequestButtonDiv">
<button id="RequestButton" name="Request" type="button">Request</button>
</div>
This calls AddToCart on my Request controller when the RequestButton button is clicked. The response is placed inside the RequestButtonDiv element.
<script type="text/javascript">
$(document).ready(function () {
$('#RequestButton').click(function (event) {
$('#RequestButton').text('Processing...');
$('#RequestButton').attr('disabled', true);
submitRequest();
});
});
function submitRequest() {
$.ajax({
url: '<%: Url.Action("AddToCart", "Request", new { id = Model.RowId, randomId = new Random().Next(1, 999999) } ) %>',
success: function (response) {
// update status element
$('#RequestButtonDiv').html(response);
}
});
}
</script>
Controller action:
public ActionResult AddToCart(int id)
{
var user = AccountController.GetUserFromSession();
user.RequestCart.AddAsset(id);
return View("~/Views/Assets/Details_AddToCart.ascx");
}
The controller returns a partial view. You could also return Content("some stuff") instead.
Holler if you have questions or need more detail.
I am looking to standardize the processing of ajax #anchors at the server side, using MVC.
Before a controller action is invoked I want to convert every request with ajax anchors into a request without ajax anchors, so that the controller code does not know there were anchors in the request:
For example:
1) /user/profile#user/photos should be treated as /user/photos
2) /main/index#user/profile/33 should be treated as /user/profile/33
What is the best technique in MVC to accomplish that?
This should necessarily be done on the client side, probably using jquery as everything that follows the # sign is never sent to the server.
I too struggle with same issue and I solved this problem after looking at Visual Studio 11 Developer Preview template code. I added following code in my _layout.cshtml, please note we must load jquery.mobile*.js file after following script tag:
<script type="text/javascript">
$(document).bind("mobileinit", function () {
// As of Beta 2, jQuery Mobile's Ajax navigation does not work in all cases (e.g.,
// when navigating from a mobile to a non-mobile page, or when clicking "back"
// after a form post), hence disabling it. http://jquerymobile.com/demos/1.0a3/#docs/api/globalconfig.html
#{
if (ViewBag.JqueryMobileAjaxEnabled != null && ViewBag.JqueryMobileAjaxEnabled == true)
{
#: $.mobile.ajaxEnabled = true;
}
else
{
#: $.mobile.ajaxEnabled = false;
}
}
});
</script>
**<script src="http://code.jquery.com/mobile/1.0b3/jquery.mobile-1.0b3.min.js"></script>**