I have a MVC Controller with an Index that will cycle through multiple PartialView as the user goes through the form process.
Here is the Index:
#section pageMain {
<div id="partialView">
#Html.Partial("SelectAccount", SUPR.Models.Account.GetAccounts());
</div>
}
This works fine and I get the SelectAccount page just fine.
My issue is that I have an AJAX call that runs when the user selects a row in a table on the SelectAccount page. What is supposed to happen is that the PartialView is then replaced with another PartialView that displays the details of the selected row. This actually does work, but after about 1 second it cycles back to the SelectAccount PartialView with a query string attached, for some reason, to the URL.
Before
After
Here is the code for the AJAX call:
$.ajax({
type: "GET",
url: "/Review/GetReviewView",
data: { profitCenter: profitCenterNo }
}).done(function (data) {
$('#partialView').html(data);
});
The ONLY that is happening in the controller for GetReviewView is that I'm returning the PartialView with the PartialView name and model. This working because, in that brief moment that I can see the ReviewAccount view, the proper data is in the fields.
Any thoughts as to why this odd behavior is occurring?
Are you capturing the event in JS? If you are triggering off of a click event then add the event parameter to the method and then at the end of the method add:
event.preventDefault()
And see if it still happens. It sounds like a client side JS issue, not a C# issue.
The way you are doing this is actually fine. There used to be a Microsoft library called ASP-AJAX or something, don't remember because I didn't use it much. This library basically allowed you to decorate HTML elements with ASP-AJAX-METHOD , ASP-AJAX-REFRESH-TYPE and it would automatically do something similar to what you are doing now. Go to the Server and retrieve a PartialView.
Related
I have an ajax call
$.ajax({
type: "POST",
data: $("#divInfoRecherche :input").serialize(),
url: '#Url.Action(Action, Controler)',
success: function(resultat) {
$("#tableauResultatRecherche").css("display", "");
$("#tableauResultatRecherche").html(resultat);
$.validator.unobtrusive.parse($('#PartialViewModel'));
}
});
The line $.validator.unobtrusive.parse($('#PartialViewModel')); makes it possible for the client side validation to pop, everything works fine.
Problem is when I click on Submit of the page, the message errors go back to the error of native JavaScript "This field is required" instead of my custom message linked in the model.
Option I think of is add the content of the partial view in the main view and populate it manually so that all the validations are added on Pageload.
But I still ask to see if another option is possible.
https://xhalent.wordpress.com/2011/01/24/applying-unobtrusive-validation-to-dynamic-content/
Here is the script to add and call on the div containing the partial view.
I have created a web calendar using HTML,CSS and C# in an MVC application. The HTML is in a view and I have a controller with an action that initializes the Calendar and displays the correct days on the view.
It works as intended but the problem comes from the fact that I want to embed this calendar to a couple of pages in unrelated Views controlled by different actions and with different models loaded.
I could copy paste the view code and make the necessary adjustments to the model but that would not be ideal. I tried with RenderAction but the problem is that when I use the buttons to navigate to different months I leave the initial view. e.g.:
#Html.ActionLink("‹", "Calendar",
new { month = Model.RequestedDateTime.Month - 1, year =
Model.RequestedDateTime.Year })
Is there a way to modify this behavior?
Thanks
Html.ActionLink, alway creates a normal link, with have the common behaviour. If you want to share your calender.
To avoid redundant code, you may redesign the calender as a partial view and replace the link by a label for example. Bind an ajax function to the label-click-event to refresh the calender. Something like:
#Html.Label("<", new { onclick="pageMonthBack("+Model.RequestedDateTime.Month - 1+", " Model.RequestedDateTime.Year+");" })
I would place the called ajax functions in a script which is loaded separately.
I solved the problem in a similar way, to what developer10214 proposed. I used a div and in that I used Render.Action. Then I used the following code
$(function () {
$("#cal").on('click', "#backwards", function () {
$.ajax({
url: "Home/Calendar?target=backwards",
cache:false,
type: "GET",
success: function (result) {
$("#cal").html(result);
}
});
});
});
in the including page. And I did not use ActionLink at all.
Let me preface this question with the fact that I am very new to MVC.
I have an instance where I am rendering a devexpress grid in a partial view.
#Html.Partial("MyGridPartial", Model)
I need to kick off a javascript function at the moment that the model has been populated via this partial view render. I attempted to do this via this. :
settings.ClientSideEvents.EndCallback
I can get to this point, but at that time I do not have the model itself populated so it does no good. I was wondering if anyone is aware of a generic way of kicking/attaching to a partial view render in order to jump into some clientside javascript code.
If it's a PartialView you're rendering in a View on the serverthen Dave's method would work best. Simply wire-up your code to the DOM ready event.
$(document).ready(function(){
//Javascript logic to fire goes here
});
or if you prever the shorthand version...
$(function(){
//Javascript logic to fire goes here
});
If you're rendering a partial view that is being loaded via Ajax then the same method will work. jQuery will run javascript in the html passed back to the client via Ajax once it's attached to the DOM if I recall correctly (feel free to test this I'm just going by memory about it firing once attached to the DOM, but I believe this is a feature of the load() method), assuming the javascript you want to run is in the response. If it's in the parent page sending the Ajax request then you're best bet is to hook it up to the complete event. (I'm populating the parameter on the client side here)
$("#wrapperAwaitingContent").load("/Grids/MyGridPartial", {id: null /*parameters*/}, function(text, status, xhr){
//Javascript logic to fire goes here
});
For me the url used in the .load() call is resolved using the UrlHelper on the server
$("#wrapperAwaitingContent").load("#Url.Action("MyGridPartial", "Grids")", {id: null /*parameters*/}, function(text, status, xhr){
//Javascript logic to fire goes here
});
You also have the option of doing something similar to this using Unobtrusive Ajax. (I'm populating the parameter on the server side here)
#Ajax.ActionLink("Load Data", "MyGridPartial", "Grids", new { id = null/*parameters*/ }, new AjaxOptions() { UpdateTargetId = "wrapperAwaitingContent", OnComplete="onCompleteMethodName" })
There are more properties you can set for the AjaxOptions other than the element to receive the HTML and the method to call when it's finished but I find I'll reuse functions defined in a shared javascript file and populate them only if they are not already populated from there, something like this...
$("a[data-ajax='true']").each(function () {
var ajaxUpdate = $(this).closest("data-ajax-container");
$(this).attr("data-ajax-update", $(this).attr("data-ajax-update") ? $(this).attr("data-ajax-update") : ajaxUpdate);
$(this).attr("data-ajax-mode", $(this).attr("data-ajax-mode") ? $(this).attr("data-ajax-mode") : "replace");
$(this).attr("data-ajax-success", $(this).attr("data-ajax-success") ? $(this).attr("data-ajax-success") : "AjaxSuccess");
$(this).attr("data-ajax-complete", $(this).attr("data-ajax-complete") ? $(this).attr("data-ajax-complete") : "AjaxComplete");
$(this).attr("data-ajax-failure", $(this).attr("data-ajax-error") ? $(this).attr("data-ajax-error") : "AjaxError");
});
If you are rendering this partial as part of the normal flow of a View being rendered, the answer is NO.
Reason for this is the Partial is converted into a string before the parent View is even rendered. At that point, none of your markup has been seen by the browser, no jscript has been read.
If, on the other hand, you rendered the partial in your JQuery Ready function:
$(document).ready(function() {
I think you would need to use an Action Partial (Partial that gets called by an action method). Action Partials can be called within your JQuery Ready function by referencing the url (restfully):
$('#divMyGridPartial').load('/Grids/MyGridPartial/{id}');
and any follow up jscript/jquery functions can be called within the ready series.
The other advantage of an Action Partial, the Model is formed within the action method and can be created contextually to what you need (ideally hinging off an id passed).
I have ajax call of action in the controller, after it update the database and it is completed successfully I can do like this:
return PartialView("Overview", mydatamodel);
and then in the the success to do like this:
success: function (data) {
// do something with the data => refresh some
// portion of your DOM
$('#someDivId').html(data);
}
And it would work fine, but what I need is that a collection in the view model to be updated, and the whole view to be rendered again with the new data.
I can do that if for instance I have submit button, then whole view is updated with the new data but if I have ajax call, how can i do that.
Here is link to my previous post where have more details:
MVC3 receiving the new model data after submit
Thank you in advance!
If you want to update the entire view don't use AJAX. Simply use a submit button. The whole point of AJAX is to update only a portion of the view without navigating away from the current page.
By the way you could redirect on the client side using window.location.href:
success: function (data) {
window.location.href = '#Url.Action("Overview", "SomeController")';
}
but there's really no need to do that if you will always redirect in the success AJAX callback. You should not use AJAX in this scenario.
You usually use AJAX precisely for the situations where you only want a portion of the view to be updated after the request completion.
If you, for some reason, need to use AJAX even for such cases (e.g. using a DELETE HTTP verb to send the request), you might do something like
window.location.href = '/Items/123';
in your success callback function, which effectively triggers a full page update.
I am using Telerik tree view control:
http://demos.telerik.com/aspnet-mvc/treeview
http://demos.telerik.com/aspnet-mvc/treeview/clientsideevents
What I want to do is set up this control on the left, then a "panel" on the right, that is a view that updates when the treeview is clicked.
So I want to do AJAX call to retrieve info from DB when a click is made in the tree view. Then I can update the "panel" with information on the current item.
How could I go about building this "panel" ? And any controls that are designed for ASP.NET MVC2 are better as that is what I am implementing this in. I saw something called UFRAME but it reminded me of IFRAME and thought I should probably avoid it.
Can I do this with a partial view, and then just the partial view area of the page updates ?
Thanks.
Telerik TreeView has:
OnSelect client side event that
you want to subscribe to and
issue an Ajax call when select happens
to your Asp.net MVC application controller action that
would return a PartialView which
you can then append to right panel
That's the process to be developed.
I've never used Telerik's controls in my life but based on the documentation on their page it seems that it works this way. Everything is basically the usual Asp.net MVC + jQuery except for the OnSelect client side event that you have to use. So nothing particularly complicated as long as Telerik's controls work as expected (which can be a story of its own).
Some code
Since I've never used Telerik, I still think this can be done something along the line:
You have your TreeView defined in one of your views like:
<%= Html.Telerik().TreeView().Name("ClientSideID") %>
Then use jQuery to do the rest:
$(function(){
$("#ClientSideID").bind("select", function(e){
e.preventDefault();
$.ajax({
url: "SomeURL",
data: e.item,
type: "POST",
success: function(partialView) {
partialView = $(partialView);
$("RightPanelSelector").append(partialView);
},
error: function(xhr, status, err){
// handle error
}
});
});
});
This code isn't tested but will get you started.