How do I refresh a second partial view, after the first partial view is updated? - ajax

I have a page which has a partial view (it's a login form). When the submit button is clicked, it calls the controller and logs the person in and refreshes the login form to show that he is logged in.
I now need to update the portion of the screen that shows the login button, or if he is logged in, shows "Hello, Logged In user"
I have a partial view written that shows whether or not the person is logged in, but I don't know how to call it after the success of the first one. I know there is an OnSuccess event, and that seems to be where I would wire that up, but I am not sure how to do this.
#using (Ajax.BeginForm("Login", "Account", new AjaxOptions { InsertionMode = InsertionMode.Replace, UpdateTargetId = "loginSection", }))
{
<div id="loginSection">
...form omitted for clarity.
<input type="submit" value="Log in" />
</div>
}
This is the partial view that needs to be updated after the login.
<ul id="menu">
#if (Request.IsAuthenticated)
{
<text>
Hello, #User.Identity.Name
</text>
}
else
{
<ul>
<a onclick="openLoginWindow()">Login</a>
<a onclick="openRegisterWindow()">Register</a>
</ul>
}

Instead of using Ajax.BeginForm, use normal form and do the form posting with your custom code so that you can controll the success handler as you wish
<div id="login">
#using(Html.Beginform())
{
<input type="text" name="UserName" />
<input type="text" name="Password" />
<input type="submit" id="btnLogin" />
}
</div>
and the script which will listen to the submit button click event and send the form the action method.
$(function(){
$("#btnLogin").click(function(e){
e.preventDefault();
var _this=$(this);
var _form=_this.closest("form");
$.post(_form.attr("action"),_form.serialize(),function(res){
if(res.Status==="authenticated")
{
//Let's hide the login form
$("#login").hide();
$("#yourSecondDiv").html(res.PartialViewContent);
}
else
{
alert("Wrong password");
}
});
});
});
So the javascript code is expecting a JSON structure like below from the controller action
{
"Status":"Authenticated",
"PartialViewContent" : "<p>The markup you want to show</p>"
}
the PartialViewContent will hold the markup you want to show to the user.
public ActionResult Login(string UserName,string Password)
{
//to do : Build the JSON and send it back
}
This answer will tell you how send the markup of a partial view in a JSON property to client.

Here is what worked for me:
Added OnSuccess:
#using (Ajax.BeginForm("Login", "Account", new AjaxOptions {
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "loginSection",
OnSuccess = "successfulLogin"
}))
{... details omitted.
Then added this:
function successfulLogin() {
$('#loginPartial').load('Account/LoginLinksPartial');
which calls in the controller:
public ActionResult LoginLinksPartial()
{
return PartialView("_LoginLinks");
}

Related

Ajax.BeginForm preload data

I have this view and everything fine with Ajax.BeginForm:
<h2>Index</h2>
#using (Ajax.BeginForm("Search", new AjaxOptions {
HttpMethod = "GET",
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "users"
})) {
<input name="q" type="text" />
<input type="submit" value="Search" />
}
<div class="table-responsive" id="users">
</div>
But, i have a little question.
Right now, when i open this page, there are no table with data - it loads only when form is submitted.
So, my question: is it possible to have preload data (without adding other code)?
When page is loaded, i would like to have already all data without filtering (input uses for filtering when value is typed and form submitted).
Just call your Search action from users div when the page loads. You may not specify any parameter or use the default one. I assume you have something like this:
public ActionResult Search(string q)
{
var users = _usersRepository.GetAll();
if(!string.IsNullOrEmpty(q))
users = users.Where(user => string.Equals(user.Name, q));
return PartialView("_Search", users);
}
And in the view:
<div class="table-responsive" id="users">
#Html.Action("Search")
</div>

mvc3 submit button not working

There is a Html.BeginForm contains Ajax.BeginForm and out side the Ajax.BeginForm there is one
submit button. But this submit button not working. If I take submit button before Ajax.BeginForm
it's working fine. Submit button inside the Ajax.BeginForm is also working fine. My question is that
why submit button is not working if I take submit button after the Ajax.BeginForm;
Thanks in advance.
#using (Html.BeginForm("AssignTestGet", "Test"))
{
using (Ajax.BeginForm("TestPreviewTemplate", "Test", new AjaxOptions { HttpMethod = "POST", InsertionMode = InsertionMode.Replace, UpdateTargetId = "template" }))
{
<button type="submit" id="questionId" name="questionId" value="#ViewBag.id" class="submit" style="margin-left:45px;margin-top:-15px;"></button>
<input type="hidden" id="templateId"value="#ViewBag.id" name="templateId" class="tr"/>
}
<div id="template">
#Html.Partial("_testTemplate", Model)
</div>
<input type="submit" value="submit" />
}
HTML do not support one form between another. It is the violation of HTML rule. So, When Parsing then it only parse Outer form not the inner Form and so the outer submit button do not work.
You can use two form Differently giving different Id.
#using (Html.BeginForm("AssignTestGet", "Home", FormMethod.Post, new { #id ="OuterForm" }))
{
<div id="template">
</div>
<input type="submit" value="submit" id="mymyb" />
}
#using (Ajax.BeginForm("TestPreviewTemplate", "Home", null, new AjaxOptions { HttpMethod = "POST", OnBegin="MyMy()", UpdateTargetId = "template" }, new { #id="innerForm"}))
{
<input type="submit" value="submit Inner" id="mymyba" />
}

Formcollection doesn't extract data from form MVC

I have trouble with formcollection.
I have some form in view, and two submit buttons both with unique name="". On debug I get on controller in formcollection all data except "name" of submitted button... I don't know why, 'cos I use this in other forms and there it works good. So I look at the code, but I couldn't find any differencies in using formcollection on not working formcol and working formcol. I tried rename buttons, move them, add referencies which I thought that could help... Nothing. On every submit skip my condition because it give me back only "false" and formcollection my "upload" or "save" button on onclick doesn't contain...
So I would like to ask you for help with this. Can you tell me where could be an error? Thanks to all!
This is in controller:
[HttpPost]
public ActionResult EditUser(EditUserVM model, int id, FormCollection c)
{
//c["upload"] is everytime set to null, 'cos c does't contain it
if (c["upload"] != null)
{
//.... some code
return RedirectToAction("Index", "Home");
}
if (ModelState.IsValid)
{
//.... next code
}
return View("EditUser", model);
}
This is in View:
#model PrukazOnline.ViewModels.EditUserVM
#{
ViewBag.Title = "EditUser";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<script type="text/javascript" src="#Url.Content("~/Scripts/jquery.validate.min.js")"></script>
<script type="text/javascript" src="#Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")"></script>
<script type="text/javascript" src="#Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")"></script>
#using (Html.BeginForm("EditUser", "User", null, FormMethod.Post, new { #class = "form-horizontal", id = "formstep", enctype = "multipart/form-data" }))
{
#*Here is some code - #Html.TextBoxFor(x => x.something) and #Html.ValidationMessageFor(x => x.something) - all of these are in formcollection*#
.
.
.
.
<div>
<input type="submit" value="Nahrát" class="upl" name="upload" id="upload" />
</div>
<div class="submit_buttons">
<input type="submit" name="save" id="save" value="Uložit" />
</div>
}
Issue is in multiple submit inputs in single form. There will only clicked button in FormCollection.
I suppose you try to vary form processing base on clicked button, in this case it's better to use different Actions for each button like this:
View:
<div>
<input type="submit" value="Nahrát" class="upl" name="upload" id="upload" />
</div>
<div class="submit_buttons">
<input type="submit" name="save" id="save" value="Uložit" />
</div>
Controller:
[HttpParamAction]
[HttpPost]
public ActionResult Upload(EditUserVM model)
{
...
}
[HttpParamAction]
[HttpPost]
public ActionResult Save(EditUserVM model)
{
...
}

partial view display with targeted div in MVC3 Razor view engine

My Controller Action is:
public ActionResult PVInPage()
{
return View();
}
public ActionResult ViewPage2()
{
return PartialView();
}
My Main View:
#using (Html.BeginForm("ViewPage2", "PartialViewInPage"))
{
<input type="submit" value="Call Page Two" />
}
<div id="DisplayPartilView">
#*display partial view *#
</div>
My Partial view Is :
#{
ViewBag.Title = "View Page 2";
}
<div style="width:500px; height:200px; background-color:Gray" >
<h1> This is my Partial view </h1>
</div>
Now I want to do : when i click submit button in my main view then my partial view arise in
My main view inner div with id="DisplayPartilView".
Thanks for response
If you want to load data/html into a page without navigating to a different page you need to use Ajax.
ASP.Net MVC provides a set of helpers to work with Ajax (they are all use jQuery.Ajax under the hood so you can always drop back to one level and write your ajax calls by hand).
But in your case the Ajax.BeginForm provides everything what you need:
So change your main view to:
#using (Ajax.BeginForm("ViewPage2", "PartialViewInPage",
new AjaxOptions() { UpdateTargetId = "DisplayPartilView" }))
{
<input type="submit" value="Call Page Two" />
}
<div id="DisplayPartilView">
#*display partial view *#
</div>
And to make it work you need to reference the following script in your main view or in your layout file after jQuery:
<script src="#Url.Content("~/Scripts/jquery.unobtrusive-ajax.js")" type="text/javascript"></script>
#using (Html.BeginForm("ViewPage2", "PartialViewInPage"))
will refresh page, that's why you need ajax
.serialize() to get data from all inputs and .ajax() to make post request, then set partial:
$('#DisplayPartilView').html(response);
In my project i am doing like this it's below
this is my button which is i click then my partial view load in my div like this
<script type="text/javascript">
$(function () {
$("#btnLode").click(function () {
$("#LodeForm").load("/City/ShowAllState", function () {
alert("Your page loaded Successfully !!!!!!!");
});
});
});
</script>
<div id="LodeForm">
</div>
and this is another solution for this problem
#using (Ajax.BeginForm("SearchCountry", "City",
new AjaxOptions
{
InsertionMode = InsertionMode.Replace,
HttpMethod = "Get",
LoadingElementId = "ajax-loader",
UpdateTargetId = "CountryListID",
}))
{
<input type="submit" value="search Country" data-autocomplete-source="#Url.Action("SearchCountry", "City")" />
}
<div id="CountryListID">
</div>
i think this will help you

MVC3 with Ajax partial view - how to display "Success" alert when creation was successfull?

I have an "Advanced Search" view. The filters configuration is an ajax partial view and the search results list is another one. On the filters configuration partial view I have a "Search" button and a "Save your search filter" submit button. I would like to display an alert saying "Save was successful" if the filter was saved in the DB, otherwise no alert at all, since any error is displayed in the dedicated area.
This is what I have so far:
AdvancedSearch.cshtml
#model MyApp.ViewModels.MyViewModel
#{
ViewBag.Title = "Advanced search";
}
<div id="divUpdateable">
#Html.Partial("_Filters", Model)
</div>
<div id="divList">
#Html.Partial("_SearchResults", Model.ResultsList)
</div>
_Filters.cshtml
#model MyApp.ViewModels.MyViewModel
<script type="text/javascript">
function ExecuteSearch() {
getForm(window.location.pathname + '/ListResults?
'&City=' + $("#txtCity").val() +
'&pCountry_ID=' + $("#ddlCountry").val() +
'&pPriceMin=' + $("#txtPriceMin").val() +
'&pPriceMax=' + $("#txtPriceMax").val() +
, 'divList');
}
</script>
#using (Ajax.BeginForm("AddOrUpdateFilter", null, new AjaxOptions
{
UpdateTargetId = "divUpdateable",
InsertionMode = InsertionMode.Replace,
OnSuccess = "ExecuteSearch",
}, new { id = "idformCreate" }))
{
#Html.ValidationSummary(false, "Some errors occured, please correct and retry.")
<p>#Html.ValidationMessage("_FORM")</p>
<div class="validation-summary-errors">
<span></span>
<ul>
</ul>
</div>
... controls...
<input id="SearchButton" type="button" value="Search" onclick="ExecuteSearch();" />
<input id="SaveButton" type="submit" value="Save your search filter" />
}
I would like to have a function to call on "OnSuccess" instead of the "ExecuteSearch" function, something like this:
function OnSuccessDoThis() {
alert("Your filter was successfully saved");
ExecuteSearch();
};
But in this form, the alert displays even if there are errors displayed in the "validation" area. How to express a condition for displaying the alert?
If http responde code is in range of 200 or 304 then it is considered successful. And onSuccess callback is called, in your case it happens alwayes because your controller is returning a valid page with code 200. You have to look with jQuery (within onSuccess callback) if there are divs with errors (e.g. count them) and if there is none it means success.
I don't remember exacly what class they have, but it would look like this:
if($("div.ErrorMessage").length > 0) { //or span.field-validation-error
// success
} else {
// failure
}

Resources