I'm wondering if this is the right way of passing a JavaScript callback function to a partial view. So depending on the view I'm on the partial view may do different things. So I pass in a JavaScript call back function to achieve that.
Here is a generic function to call my partial view and where I pass in the JavaScript call back function.
function showAjaxMessage(targetDiv, ajaxMessage) {
var ajaxLoader = "<img src='Content/loader.gif' alt=''>";
$(targetDiv).html("<p>" + ajaxLoader + " " + ajaxMessage+"</p>");
}
function getPartialView(actionUrl, targetDiv, ajaxMessage, cbFunc) {
showAjaxMessage(targetDiv, ajaxMessage);
$.get(actionUrl, { callback: eval(cbFunc).toString()}, function(result) {
$(targetDiv).html(result);
});
}
Here is an example of me calling it:
getPartialView("Home/OpenLogin", "#divLogon", "Loading...", function() { alert('This is the call back function!'); test(); });
Here is the controller where I get the callback function and save it to a model. Then I pass it back to the partial view.
// returns a login dialog which will be injected
// into a placeholder div on the client
public ActionResult OpenLogin(string callback)
{
var baseModel = new BaseModel();
baseModel.cbFunc = callback;
return PartialView("LoginDialog", baseModel);
}
Here is an example of my partial view. Where you can see I get the call back function and set in the init function.
#model MvcApplication8.Models.BaseModel
function init(cb){
if(cb!=undefined){
cb();
}
else{
alert("undefined");
}
}
function test(){
alert("Testing my call back");
}
$(function () {
init(#Html.Raw(#Model.cbFunc));
});
The solution above works, but the main question that comes to mind is this the right way of doing it? Passing the call back function from the controller to the partial view sounds wrong, but how else would you do it? Any ideas?
Based on your example, I do not understand why would pass the callback function to a partial view. The partial view is rendered inside a div on the same page. Why not just declare the function on the page so that it's available to the rendered partial view?
Related
I have a java script function that calling a controller method using Ajax, this call should get me the user profile page, I have a controller for this purpose. When I run the program and fire the java script function it's trigger the controller and every thing is good but when the debugging has ended no changes happens and the view doesn't present in the screen.
I tracked the call and every thing is working fine, passing parameter and reaching the method in the controller.
Note: the view which has the JS call related to a different controller.
View contain java script call:
<td onclick="ViewProfile('#item.CustomerId')"></td>
Java script file
function ViewProfile(id) {
console.log("sucsses");
$.ajax({
type:"GET",
url: "/ViewUserProfile/Index",
data: { "userId": id }
});
};
Controller: ViewUserProfileController
public ActionResult Index(string userId)
{
var ProfileInformation = new UserProfileVM
{
//some logic here
};
return View(ProfileInformation);
}
You are fetching ViewUserProfile in $.ajax but you are not using .done(function() { }) to process the result you receive from that call.
In your case I would simply suggest to use window.location.href in ViewUserProfile() as below.
function ViewProfile(id) {
window.location.href = "/ViewUserProfile/Index?userId=" + id;
}
I am building a Single Page Application using ASP.NET and sammy.js, where all views except for the Home/Index view are rendered as partial views so that sammy can swap out the content of the main body with the partial view that is returned.
I am using the example given here, and everything loads fine as expected.
Similar to the above example, in my Home/Index page I have reference to a script called routing.js, which wraps the sammy function call in order to parse the MVC route:
var Routing = function (appRoot, contentSelector, defaultRoute) {
function getUrlFromHash(hash) {
var url = hash.replace('#/', '');
if (url === appRoot)
url = defaultRoute;
return url;
}
return {
init: function () {
Sammy(contentSelector, function () {
this.get(/\#\/(.*)/, function (context) {
var url = getUrlFromHash(context.path);
context.load(url).swap();
});
}).run('#/');
}
};
}
I need to call a callback function after the content swap has fully completed in order to implement further jQuery functionality on the newly rendered content. My dilemma is that no matter what option I try from the sammy.js docs, nothing seems to run the callback after the content has been swapped.
I have tried all of the following (all "valid" ways of passing a callback according to the sammy.js docs):
content.load(url).swap(pageLoadScripts(url));
content.load(url).swap().onComplete(pageLoadScripts(url));
content.load(url).swap().then(pageLoadScripts(url));
content.load(url).swap().next(pageLoadScripts(url));
content.load(url,pageLoadScripts(url)).swap();
and even
content.load(url).swap();
pageLoadScripts(url);
In every case the pageLoadScripts function fires off prior to the content being swapped. Any ideas or suggestions on what to do differently?
This is a bit of a hack, but it works.
Inside the Sammy initialization function, I added the following override to the swap function just before the override to the get function:
this.swap = function (content, callback) {
var context = this;
context.$element().html(content);
pageLoadScripts(hashedUrl);
};
FWIW, I still have not been able to get callback to be anything other than 'undefined', even in this override function.
Managed to get this working:
// override for callback after page load
this.swap = function(content, callback) {
this.$element().html(content);
if (callback) {
callback();
}
};
// users
this.get('/#/users', function(context) {
context.load('/users').swap(function() { replaceBindings(viewModel.users); });
});
I managed to get the callback param to NOT be 'undefined' by wrapping it in another function.
I have this jquery function placed in my .js file.... As long as my page is loaded this works... but when i changed it to return as a partial view.... this alert wont work anymore... How is it gonna be working again ?
$(document).ready(function () {
var msg = '#ViewBag.Message';
if (msg == '1')
alert("New Time Shift has been saved.");
});
In my controller action...
if (Request.IsAjaxRequest())
return PartialView("_RecordList", userRecord); //alert wont work here...
return View(userRecord); //this will return the whole view thus the alert works here
The document ready function will not be executed from ajax requests.
You could extract the javascript code to a separated function part of the whole view. You can also create a callback function to be executed when the partial request succeeds, that will also call it:
$(document).ready(function () {
var msg = '#ViewBag.Message';
initFunction(msg);
});
function initFunction(msg){
if (msg == '1')
alert("New Time Shift has been saved.");
}
function partialRequestSuccess(data){
//store the message somewhere in the partial view, like a hidden div and get it using jquery
var msg = ...
initFunction(msg);
}
Then you could set the complete callback of the ajax request to call the success callback we have just created. If you are using the MVC ajax helpers, there is a Success parameter that you can set like:
#using(Ajax.BeginForm(new AjaxOptions{ OnSuccess = "partialRequestSuccess" }))
I have this jquery function placed in my .js file....
var msg = '#ViewBag.Message';
This is server code, that works only in *.cshtml files, this is minimum one problem.
Ok, I have a controller that returns a response to an ajax call and I'd like to intercept that response in my view. How can I do this?
Alternatively, how could i reference my ajax variable in my view?
View: ContractorList.ascx
Controller: HaulerController.cs
Not sure exactly what you're asking, but I think the answer is something along the lines of this:
$.get("/url/to/action", {/* data you're passing to action */}, function (response) {
// your result is available here....
// you want to pass it into the callback method as an argument, as above
// everything your action returns to the page is stored in the response object.
// can you do something like:
var idx = response.indexOf('specific string I expect');
if (idx > -1)
// the string you expected is there so show popup....
}, "html");
return false;
});
If this isn't what you're after, please clarify
I have an asp.net mvc application. When button is clicked (submit button) I would like to results to be displayed inside some div. I know how to do it. I have some action where I return a partial view. But when button is submitted then I get some multiple objects from db and I would like to display them all in div.
How can I achieve it?
Your action method could serialize and return them as a JSON encoded string:
public ActionResult Foo()
{
SomeEntity[] entities = FetchEntities();
// The JsonRequestBehavior is necessary only in ASP.NET MVC 2.0
return Json(entities, JsonRequestBehavior.AllowGet);
}
which could be invoked like this:
$.getJSON('/home/foo', function(json) {
$(json).each(function(index, value) {
// SomeProperty is a property of your entity:
$('body').append('<div>' + value.SomeProperty + '</div>');
});
});
Wrap all those objects in a wrapper object and pass that object to your partial view. Strongly type your partial view to the wrapper object and you are done!