Reputation: 5524
-- Running within ASP.NET MVC alongside jQuery --
I'm using jQuery to render a <LI>
block as a list of dropdown menu items. There are 3 items in that list if the user is _not logged in - 4 items if he _has logged in. That 4th item needs to run a couple conditionals before it can decide exactly what payload it carries so I have that code in a .ascx control and the main page calls:
<div id="loginBox">
<% Html.RenderPartial("showLoginStatus"); %>
</div>
so as to decide how to render it.
This much is working as long as I'm willing to wait for a postback that follows the AJAX-based login. What I need to do now is get the code to run without the page refresh.
The part of the page that displays either the login button or the user's name looks like:
var form = $("#loginForm");
form.submit(function() {
var data = form.serialize();
$.post(form.attr("action"), data, function(result, status) {
if (result.Success) {
$(".showLoggedUser").html(result.UserName + '<br /><a href="/Admin/Account/LogOut">Log Out</a>');
//how can I force the code contained in 'showLoginStatus.ascx' to render at this point?
api.close();
} else {
$('.loginErrors').html(result.ErrorMessage);
}
}, "json");
return false;
});
});
Upvotes: 0
Views: 875
Reputation: 24108
You can return the HTML of the ShowLoginStatus.ascx in the result (JSON probably).
Here is how you can render the view into string to accompish that.
Another approach is to return different content types from the action depending on the result.
So your JavaScript will look like:
var form = $("#loginForm");
form.submit(function() {
var data = form.serialize();
$.post(form.attr("action"), data, function(result, status) {
// Write your isJson function to check the result type
if (!isJson(result)) {
$(".showLoggedUser").html(result);
api.close();
} else {
$('.loginErrors').html(result.ErrorMessage);
}
}); // DO NOT SPECIFY RESULT TYPE
return false;
});
});
Upvotes: 1
Reputation: 10581
What about if the ajax request was to return a Partial view that included the showLoginStatus content?
i.e. Have an action that the ajax calls which returns a PartialView (.ascx) and that Partial view is made up of the showLoginStatus view and any extra markup you need.
Maybe have a look at Ajax.ActionLink and the AjaxOptions parameter to get some other ideas?
Upvotes: 0