ASP.NET MVC 2 Use Ajax to reload a UserControl - ajax

is it possible to use Ajax with ASP.NET MVC 2 to reload a user control, pass along a new Model and have it update all the values that make use of this model without refreshing the rest of the site content?

Yes, and here is one way to do so:
You can call an action on a controller from ajax (jquery is what I use) and get the result. To pass data up you provide parameter values to the $.ajax() call and rendering back you just render a partial with whatever viewmodel is appropriate to your partial.
To get the content displayed you just take the HTML result passed back to your $.ajax() call and, most commonly, replace the contents of a div with your HTML result.

I got it working!
I have the following code in the Controller:
[Authorize, HttpPost]
public ActionResult UpdateDinner(FormCollection formValues)
{
if (Request.IsAjaxRequest())
{
Dinner Dinner = DinnerRepository.GetDinner(Convert.ToInt32(formValues["Date"]));
return PartialView("DeclaratieWidget", Dinner);
}
}
I have this code in my View:
<script src="<%= AppPathHelper.Url(Request.ApplicationPath, "/Scripts/MicrosoftAjax.debug.js") %>" type="text/javascript"></script>
<script src="<%= AppPathHelper.Url(Request.ApplicationPath, "/Scripts/MicrosoftMvcAjax.debug.js") %>" type="text/javascript"></script>
<% using (Ajax.BeginForm("UpdateDinner", new AjaxOptions { UpdateTargetId = "Dinner" }))
{ %>
<select id="Date" name="Date">
<option value="<%= Dinner.Dinner_ID %>"><%= Dinner.Date.ToString("dddd d MMMM") %></option>
</select>
<input type="submit" value="Delete" />
<div id="avondeten">
<% Html.RenderPartial("DeclaratieWidget", Model.Dinners[0]); %>
</div>
It works perfectly this way! :D

Related

Prevent reload on Ajax.BeginForm

How can I prevent page reloading when submitting form in partial view? There are a lot of examples but it seems that non of them is working for me. This is what I have. Partial view (Razor) which calls this:
#using (Ajax.BeginForm("SaveReply", "Home", null, new AjaxOptions { HttpMethod = "Post" }, new { target = "_self" }))
{
<div class="input-group wall-comment-reply" style="width:100%">
#Html.Hidden("eventid", #item.EventID)
<input name="txtReply" type="text" class="form-control" placeholder="Type your message here...">
<span class="input-group-btn">
<button class="btn btn-primary" id="btn-chat" type="submit">
<i class="fa fa-reply"></i> Reply
</button>
</span>
</div>
}
Then I have my action method in the controller:
[HttpPost]
public void SaveReply(string txtReply, string eventid)
{
//some code
}
The controller action is fired but after that it is automatically redirected to localhost/home/SaveReply
Maybe the problem is that this partial view is rendered from string. I took the code from:
How to render a Razor View to a string in ASP.NET MVC 3?
Also amongs other things i tried this:
http://geekswithblogs.net/blachniet/archive/2011/08/03/walkthrough-updating-partial-views-with-unobtrusive-ajax-in-mvc-3.aspx
I would appreciate any help.
I found the problem.
It seems that you need to reference the Unobtrusive scripts. Just install them from NuGet:
Install-Package Microsoft.jQuery.Unobtrusive.Ajax
And then reference it from the View that calls the Partial View:
<script src="~/Scripts/jquery.unobtrusive-ajax.min.js"></script>
And miraculosly it works without any other changes. More explanations can be found here:
[Why does Ajax.BeginForm replace my whole page?
and here:
[Why UnobtrusiveJavaScriptEnabled = true disable my ajax to work?
It seems that you need to use it if you are using Ajax.* helpers in MVC 3 and higher.

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

Ajax with partial view: getting complete postback

I have a view in which I am attempting to do an ajax call (using MVC Ajax support) and insert the returned partial view into a div on the page. As far as I can tell, what I'm doing is very by-the-book. But instead of an Ajax call and an updated div, I'm getting a full postback.
Here's the relevant chunk of the view:
<fieldset>
<legend>Available Instructors</legend>
<p>
#{ using (Ajax.BeginForm("InstructorSearch", "CourseSection", new AjaxOptions() { UpdateTargetId = "divSearchResult" }))
{
#Html.Raw(" Search: ")
<select id="SearchType" name="SearchType">
<option value="Last" #( (ViewBag.SearchType == "Last") ? " selected" : "")>Last Name</option>
<option value="First" #( (ViewBag.SearchType == "First") ? " selected" : "")>First Name</option>
</select>
#Html.Raw(" ")
<input type="text" id="SearchText" name="SearchText" value="#( ViewBag.SearchText)" />
#Html.Raw(" ")
<input type="submit" id="Search" name="Search" value="Search" />
}
}
</p>
<div id="divSearchResult"></div>
</fieldset>
Here's the method on the controller:
[HttpPost]
public PartialViewResult InstructorSearch(string searchType, string searchText)
{
var list = Services.InstructorService.ListInstructors(
base.CurrentOrganizationId.Value,
(searchType == "First") ? searchText : null,
(searchType == "Last") ? searchText : null,
0,
Properties.Settings.Default.InstructorListPageSize
);
return PartialView(list);
}
I've checked, and I'm loading MicrosoftAjax.js and MicrosoftMvcAjax.js.
So I'm stumped. I know that I can do all this in jQuery quite easily, and I've done that elsewhere, but this is a situation where, for reasons not worth getting into, if this could be made to work it would be the simplest, cleanest, easiest-to-understand solution.
I've checked, and I'm loading MicrosoftAjax.js and MicrosoftMvcAjax.js.
Those scripts are obsolete in ASP.NET MVC 3. You can completely remove them from your site. They are useless. They are included only for backwards compatibility if you were upgrading from previous versions in which case you must explicitly disable unobtrusive AJAX in your web.config:
<!-- Remark: don't do this => only for demonstration purposes -->
<add key="UnobtrusiveJavaScriptEnabled" value="false"/>
In ASP.NET MVC 3, Ajax.* helpers use jQuery by default. So must reference the jquery.unobtrusive-ajax.js which is what makes Ajax.* helpers work:
<script src="#Url.Content("~/Scripts/jquery.unobtrusive-ajax.js")" type="text/javascript"></script>

MVC3 with Ajax - return data not "plugged" to the right spot

I'm trying to get started with Ajax on MVC
In my main view I have the following code:
#Ajax.ActionLink("Click here to get the data","LoadData",
new AjaxOptions
{
UpdateTargetId = "dataPanel",
InsertionMode = InsertionMode.InsertAfter,
HttpMethod="GET"
})
<div id="dataPanel">
</div>
I created the controller's action as below:
public PartialViewResult LatestReview()
{
var myData = GetMyData();
return PartialView("_PartialData", myData);
}
_PartialData is defined as below:
#model MyApp.Models.Data
<div>
#if (Model == null)
{
<p>There is no data yet</p>
}
else
{
<p>
#Model.Body
</p>
}
</div>
But when I click the link, my data (rendered in the _PartialData) is loaded fully in browser, replacing the source page (so not inside the dataPanel div)
When I look at original page source (before clicking the ajax link) It see the ajax actions define as below:
<a data-ajax="true" data-ajax-method="GET" data-ajax-mode="after" data-ajax-update="#dataPanel" href="/Home/LoadData">Click here to get the data</a>
<div id="dataPanel">
</div>
What am I doing wrong?
Thanks
I suspect that you forgot to include the jquery unobtrusive ajax script to your page:
<script src="#Url.Content("~/Scripts/jquery.unobtrusive-ajax.js")" type="text/javascript"></script>
It is this script that makes sense of all Ajax.* helper in ASP.NET MVC 3. Without it they generate standard markup with HTML5 data-* attributes which are used by the script.

MVC3 Razor Partial view render does not include data- validation attributes

I have a farily straight forward form that renders personal data as a partial view in the center of the form. I can not get client side validation to work on this form.
I started chasing down the generate html and came up with the same model field rendered on a standard form and a partial view.
I noticed that the input elements are correctly populated on the first call, #html.partial, the following only happens when the partialview is reloaded via an ajax request.
First the header of my partial view, this is within a Ajax.BeginForm on the main page.
#model MvcMPAPool.ViewModels.EventRegistration
<script src="#Url.Content("~/Scripts/jquery.validate.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.validate.unobtrusive.js")" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function ()
{
$(".phoneMask").mask("(999) 999-9999");
});
</script>
#{
var nPhn = 0;
var dTotal = 0.0D;
var ajaxOpts = new AjaxOptions{ HttpMethod="Post", UpdateTargetId="idRegistrationSummary", OnSuccess="PostOnSuccess" };
Html.EnableClientValidation( true );
Html.EnableUnobtrusiveJavaScript( true );
}
Here is the razor markup from the partial view:
#Html.ValidationMessageFor(model=>Model.Player.Person.Addresses[0].PostalCode)
<table>
<tr>
<td style="width:200px;">City*</td>
<td>State</td>
<td>Zip/Postal Code</td>
</tr>
<tr>
<td>#Html.TextBoxFor(p=>Model.Player.Person.Addresses[0].CityName, new { style="width:200px;", maxlength=50 })</td>
<td>
#Html.DropDownListFor(p=> Model.Player.Person.Addresses[0].StateCode
, MPAUtils.GetStateList(Model.Player.Person.Addresses[0].StateCode))</td>
<td>
<div class="editor-field">
#Html.TextBoxFor(p=>Model.Player.Person.Addresses[0].PostalCode, new { style="width:80px;", maxlength=10 })
</div>
</td>
</tr>
</table>
Here is the rendered field from the partial view:
<td>
<div class="editor-field">
<input id="Player_Person_Addresses_0__PostalCode" maxlength="10" name="Player.Person.Addresses[0].PostalCode" style="width:80px;" type="text" value="" />
</div>
</td>
Here is the same model field rendered in a standard view:
<div class="editor-field">
<input data-val="true" data-val-length="The field Postal/Zip Code must be a string with a maximum length of 10." data-val-length-max="10" data-val-required="Postal or Zip code must be provided!" id="Person_Addresses_0__PostalCode" maxlength="10" name="Person.Addresses[0].PostalCode" title="Postal/Zip Code is required" type="text" value="" />
<span class="field-validation-valid" data-valmsg-for="Person.Addresses[0].PostalCode" data-valmsg-replace="true"></span>
</div>
Notice that the partial view rendering has no data-val-xxx attributes on the input element.
Is this correct? I do not see how the client side validation could work without these attributes, or am I missing something basic here?
In order to create the unobtrusive validation attributes, a FormContext must exist. Add the following at the top of your partial view:
if (this.ViewContext.FormContext == null)
{
this.ViewContext.FormContext = new FormContext();
}
If you want the data validation tags to be there, you need to be in a FormContext. Hence, if you're dynamically generating parts of your form, you need to include the following line in your partial view:
#{ if(ViewContext.FormContext == null) {ViewContext.FormContext = new FormContext(); }}
You then need to make sure you dynamically rebind your unobtrusive validation each time you add/remove items:
$("#form").removeData("validator");
$("#form").removeData("unobtrusiveValidation");
$.validator.unobtrusive.parse("#form");

Resources