Ajax with partial view: getting complete postback - ajax

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>

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.

How to show flash.message in Grails after AJAX call

I want to show some flash message after completion of AJAX call. I am doing like this ..
Controller Action --
def subscribe()
{
def subscribe = new Subscriber()
subscribe.email = params.subscribe
if (subscribe.save())
{
flash.message = "Thanks for your subscribtion"
}
}
View Part --
Subscribe :
<g:formRemote onSuccess="document.getElementById('subscribeField').value='';" url="[controller: 'TekEvent', action: 'subscribe']" update="confirm" name="updateForm">
<g:textField name="subscribe" placeholder="Enter your Email" id="subscribeField" />
<g:submitButton name="Submit" />
</g:formRemote >
<div id="confirm">
<g:if test="${flash.message}">
<div class="message" style="display: block">${flash.message}</div>
</g:if>
</div>
My AJAX working fine but it is not showing me flash.message. After refresh page it displaying message. How to solve it ?
When you use ajax your page content isn't re-parsed, so your code:
<g:if test="${flash.message}">
<div class="message" style="display: block">${flash.message}</div>
</g:if>
will not run again.
So I agree with #James comment, flash is not the better option to you.
If you need to update your view, go with JSON. Grails already have a converter that can be used to this:
if (subscribe.save()) {
render ([message: "Thanks for your subscribtion"] as JSON)
}
And your view:
<g:formRemote onSuccess="update(data)" url="[controller: 'TekEvent', action: 'subscribe']" name="updateForm">
<g:textField name="subscribe" placeholder="Enter your Email" id="subscribeField" />
<g:submitButton name="Submit" />
</g:formRemote >
<script type='text/javascript'>
function update(data) {
$('#subscribeField').val('');
$('#confirm').html(data.message);
}
</script>
You have couple options,
First you can try to return the message from your controller in a form of json or a map and render it on the screen your self using javascript libraries, which is a bit different if you want to use Grails ajax tags.
The other option is using a plugin like one-time-data , which
Summary A safe replacement for "flash" scope where you stash data in
the session which can only be read once, but at any point in the
future of the session provided you have the "id" required.
Description
This plugin provides a multi-window safe alternative to flash scope
that makes it possible to defer accessing the data until any future
request (so long as the session is preserved).
more
Hope it helps

MVC3 - Understanding POST with a button

How does one obtain the form data after submitting it?
<form target="_self" runat="server">
<p>
<select id="BLAHBLAH2">
<option>2010</option>
<option>2011</option>
<option>2012</option>
<option>2013</option>
</select>
<input type="submit" runat="server" value="Change Year" />
</p>
</form>
This hits the controller's Index method. But, there's nothing in Request.Form. Why?
Second, can I use
<input type="button" instead of type=submit? That is, without introducing ajax via onclick.
Finally, how do I submit to a different method in the controller, e.g. Create?
Try removing those runat server tags. They should not be used in ASP.NET MVC. Also your select doesn't have a name. If an input element doesn't have a name it won't submit anything. Also your option tags must have value attributes which indicates what value will be sent to the server if this options is selected:
<form action="/Home/Create" method="post">
<p>
<select id="BLAHBLAH2" name="BLAHBLAH2">
<option value="2010">2010</option>
<option value="2011">2011</option>
<option value="2012">2012</option>
<option value="2013">2013</option>
</select>
<input type="submit" value="Change Year" />
</p>
</form>
But the correct way to generate forms in ASP.NET MVC is to use HTML helpers. Depending on the view engine you are using the syntax might be different. Here's an example with the Razor view engine:
#model MyViewModel
#using (Html.BeginForm("Create", "Home"))
{
<p>
#Html.DropDownListFor(x => x.SelectedYear, Model.Years)
<input type="submit" value="Change Year" />
</p>
}
Here you have a strongly typed view to some given view model:
public class MyViewModel
{
public string SelectedYear { get; set; }
public IEnumerable<SelectListItem> Years
{
get
{
return Enumerable
.Range(2010, 4)
.Select(x => new SelectListItem
{
Value = x.ToString(),
Text = x.ToString()
});
}
}
}
which is populated by some controller action that will render this view:
public class HomeController: Controller
{
public ActionResult Index()
{
var model = new MyViewModel();
return View(model);
}
[HttpPost]
public ActionResult Create(MyViewModel model)
{
... model.SelectedYear will contain the selected year
}
}
None of your <option> tags have a value:
...
<option value="2010">2010</option>
...
As noted by David, runat="server" is most definitely a WebForms thing, so you can 86 that.
If you want to submit to a different method on your controller you just need to specify the URL for that method.
Easy way using Html.BeginForm:
#using (Html.BeginForm("AnotherAction", "ControllerName")) {
<!-- Your magic form here -->
}
Using Url.Action
<form action="#Url.Action("AnotherAction")" method="POST">
<!-- Your magic form here -->
</form>
You can also use
In Controller
int Value = Convert.ToInt32(Request["BLAHBLAH2"]); //To retrieve this int value
In .cshtml file use
<select id="IDxxx" name="BLAHBLAH2">
//Request[""] will retrieve the VALUE for the html object ,whose "name" you request.

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");

ASP.NET MVC 2 Use Ajax to reload a UserControl

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

Resources