Post form data to Controller's action with Ajax - ajax

I have a page in MVC3, with a link (Ajax.ActionLink). When user clicks it, it calls controller's action, and the result is inserted into a div, with replace.
Code is shown below:
#Ajax.ImageActionLink("/Images/btn_share.png", "Share pool", "SharePool", new { poolKey = Model.Id, poolName = Model.Name },
new AjaxOptions {
UpdateTargetId="popup",
HttpMethod="GET",
InsertionMode = InsertionMode.Replace,
LoadingElementId="loading_dialog",
OnSuccess = "ShowPopup('#popup_share', true, true)"
}
ImageLinkAction is custom extension method to use image as link, and ShowPopup is a javascript function that shows the updated div (to make it look as a popup)
Now the markup code inserted into the div which creates the popup contains a form as below
<div>
#using (Html.BeginForm()) {
#Html.HiddenFor(model => model.ID)
<div class="editor-label">
#Html.LabelFor(model => model.EmailAddress)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.EmailAddress)
#Html.ValidationMessageFor(model => model.EmailAddress)
</div>
// ... other fields
#Html.ValidationSummary(true)
<p>
<button type ="submit">Share</button>
</p>
}
</div>
The issue is with the form's submit: the Submit button calls the proper action but with a postback, which cause my page to refresh. What I need is to post data with ajax, receive the response, which is another partial view that gets inserted into the
I was trying to replace the Submit button with Ajax.ActionLink as below
#Ajax.ActionLink("Share", "Share",
new Models.MyModel
{
ID = Model.ID,
EmailAddress = Model.EmailAddress
},
new AjaxOptions
{
UpdateTargetId="popup",
HttpMethod="POST",
InsertionMode = InsertionMode.Replace,
LoadingElementId="loading_dialog",
OnSuccess = "ShowPopup('#popup_share', true, true)"
}
The controller's code looks like this:
[HttpPost]
public ActionResult SharePool(MyModel model)
{
// ...
return PartialView("_MyPartialView", model)
}
The problem is, in the moment the Ajax ActionLink is rendered (when form is loaded) there is no value in Model.EmailAddress, so my POST action in controller receives only ID parameter.
How can I handle this? Ideally, I think I should add
OnBegin = "PreparePostData()"
But since I know javascript only basically, I have no idea how can I implement this. I think this PreparePostData() should collect form fields and prepare the object routeValues parameter, to be set before the ajax call is invoked.
Anyone can give me some indications on how to implement this?
Or is any other, better approach on this problem?
Thank you

I'd recommend just writing your own AJAX calls with jQuery. It's more flexible than MVC's helpers anyway
#Html.ActionLink("Share", "Share", new { }, new { id = "share" })
And then a function
$("#share").click(function (e) {
e.preventDefault();
//Show loading display here
var form= $("#shareForm");
$.ajax({
url : '#Url.Action("Share")',
data: form.serialize(),
type: 'POST',
success: function(data){
//Show popup
$("#popup").html(data);
}
});
});

When you do have multiple Forms on same Page (imagine the case y're showing/hiding on demand), you need to add Form before the #Id as Follows :
$("#share").click(function (e) {
e.preventDefault();
//Show loading display here
// Need to add Form before #id
var form= $("Form#share");
$.ajax({
url : '#Url.Action("Share")',
data: form.serialize(),
type: 'POST',
success: function(data){
//Show popup
$("#popup").html(data);
}
});
);

Related

mvc3 ajax prepoluate textbox

I have a controller that uses ajax.actionlink in order to get a partial view from another controller. My question is how can I use the result from that ajax partialview to fill in a textbox in my main action .
This is the view i'm working on corresponds to this view
#Ajax.ActionLink("Find location", "getzipcode",
new AjaxOptions
{
UpdateTargetId = "ajax_insert",
InsertionMode = InsertionMode.Replace,
HttpMethod = "GET"
});
<div id="ajax_insert">
</div>
#using (Html.BeginForm("create", "service", FormMethod.Post))
{
// fill Ajax code in this EditFor Result
#Html.EditorFor(model => model.zipcode)
}
as you can see above that ajax simply request's a partial view called getzipcode which just links to this action
public PartialViewResult getzipcode()
{
var zipco = (from s in db.servicers where s.zipcode == 32839 select s);
return PartialView("_review", zipco);
}
The ajax works correctly, im just stumped on inserting the zipcode into the EditFor box as well I tried
#Html.EditorFor(model => model.zipcode,#ajax_insert) but it did not work.
You can make use of onSuccess callback function
#Ajax.ActionLink("Find location", "getzipcode",
new AjaxOptions
{
UpdateTargetId = "ajax_insert",
InsertionMode = InsertionMode.Replace,
HttpMethod = "GET",
OnSuccess = "fillTextBox"
});
<script type="text/javascript>
function fillTextBox(){
//Use jquery to fill your text box
}
</script>

ASP MVC-3 : Problems updating the data of an AJAX form after making a post

I have the following problem when updating a for via AJAX after it is submitted. For some reason some hidden fields that are on the HTML that is returned are not being updated, which is weird because when I run the debugger they appeared to have the correct value.
This is the relevant part of my form
<div id="itemPopUpForm">
#{Html.EnableClientValidation();}
#Html.ValidationSummary()
<div id="formDiv">
#{ Html.RenderPartial("ItemData", Model, new ViewDataDictionary() { { "Machines", ViewBag.Machines }, { "WarehouseList", ViewBag.WarehouseList }, { WebConstants.FORM_ID_KEY, #ViewData[WebConstants.FORM_ID_KEY] } }); }
</div>
</div>
Then the partial view contains hidden fields like these which are the ones not being updated
#using (Html.BeginForm("Index", "Item", FormMethod.Post, new { id = "frmItem", name = "frmItem" }))
{
#Html.AntiForgeryToken()
#Html.HiddenFor(model => model.Item.SodID)
#Html.HiddenFor(model => Model.Item.ItemID) //The itemID needs updating when an item is copied
#Html.HiddenFor(model => model.Item.Delivery.DeliveryAddressID, new { #id = "delAddressID" })
And this is the javascript method that updates the form
function ajaxSave() {
if (!itemValid()) return;
popup('ajaxSplash');
$.ajax({
type: "POST",
url: '#Url.Action("Index")',
data: $("#frmItem").serialize(),
success: function (html) {
console.log(html);
$("#formDiv").html(html);
initItemPage();
alert("Item was saved successfully");
},
error: function () { popup('ajaxSplash'); onFailure(); }
});
}
The action Index returns the Partial View "ItemData" and when I check the Item Model it does have the correct value, but when I see the html returned it is still set to 0.
If you intend to modify a model property in your POST action don't forget to remove it from ModelState first, otherwise HTML helpers will use the originally posted value when rendering:
[HttpPost]
public ActionResult Index(MyViewModel model)
{
// remove the value from modelstate
ModelState.Remove("Item.ItemID");
// update the value
model.Item.ItemID = 2;
return PartialView(model);
}
I'm having the same problem and it seems like the helper HiddenFor evaluates with required unobtrusive validation even if in the model one does not annotate the property with [Required].
The HTML rendered by #Html.HiddenFor(m=>m.Step) is :
<input data-val=​"true" data-val-number=​"The field Step must be a number." data-val-required=​"The Step field is required." id=​"Step" name=​"Step" type=​"hidden" value=​"2">​
Hence, it is why it works if we remove it from the ModelState.
Removing the property from the ModelState seems to me like a hack. I would prefer to use
<input type="hidden" id="Step" name="Step" value="#Model.Step" />
instead of the Html.HiddenFor helper.
You can also implement you own HiddenFor helper.

Using Fancybox with ASP.NET MVC Ajax

I have a form which loads within a fancybox so that if the user clicks on a link, a form loads up in fancybox, its an #Ajax.BeginForm(). Like so:
#using (Ajax.BeginForm("AddToBasket", new { controller = "Orders" }, new AjaxOptions()
{
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "SuccessBasket",
OnSuccess = "goToCheckout"
}, new { #class = "product-order-form" }))
{
#* Form elements for Model *#
<div id="SuccessBasket"></div>
}
This gets loaded up in a fancybox window. When I submit the form, my SuccessBasket div does not get updated with the new content passed from the controller, is there some way to enable Ajax calls to be updated within Fancybox? This works fine if I don't use fancybox but I wish to use it.
EDIT:
The form is loaded like so:
#Ajax.ActionLink("Order", "OrderProduct", new { controller = "Orders", id = ViewData["ID"], search = ViewData["search"] }, new AjaxOptions()
{
UpdateTargetId = "ModalWindow",
InsertionMode = InsertionMode.Replace,
OnFailure = "NotAuthorised"
}, new { #class = "lightbox order-link" })
I have an empty div called ModalWindow which is wrapped by a div set to display: none as per the instructions:
<div style="display: none">
<div id="ModalWindow">
</div>
</div>
OrderProduct Action in my controller returns a PartialView:
return PartialView("_OrderProduct", basket);
Where basket is my model BasketModel basket = new BasketModel();
My _OrderProduct PartialView is the view which contains the Ajax form at the start of my post. Which has the SuccessBasket div.
Upto this point, it works perfectly. The form loads up in fancybox.
The AddToBasket Action returns a PartialView:
return PartialView("_BasketSuccess");
This view simply tells the user that their item was added to the basket:
<p>This item has been added to your basket. Search again or goto #Html.ActionLink("checkout", "Order", new { controller = "Orders" }, new { #class = "checkout-link" }) to continue.</p>
The problem is, the SuccessBasket div does not update with the text above but through debugging, I can see that it does load the view _BasketSuccess, it just doesn't update in the modal window.
The way you are loading the fancybox is strange. You are sending 2 AJAX requests: one for the Ajax.ActionLink and one by the fancybox. All that is not necessary. Also you don't need a hidden div in your main view, the fancybox does all this automatically.
So to recap, in your main view all you need is a simple HTML link to the controller actin which will return a partial containing the form:
#Html.ActionLink("Order", "OrderProduct", "Orders", null, new { #class = "lightbox" })
and in a separate javascript file you will attach the fancybox to this anchor so that when it is clicked it will automatically send an AJAX request (the fancybox, not you), fetch the partial form and show it:
$(function () {
$('.lightbox').fancybox();
});
Alright, now you have a partial form shown in a fancybox. This partial form is actually an Ajax.BeginForm. So when you submit this form it will send an AJAX request to the AddToBasket action and upon success it will update the <div id="SuccessBasket"></div> which is inside this form with the result returned by this action.

Close modal window containing ASP MVC Ajax form

in a webapp I'm using an ASP MVC Ajax form in a modal window. I do not use any specific jQuery code, only some to open the modal window (i.e. showModal() function):
#Ajax.ActionLink("Open", "Add", "Home", new {id = Model.Id}, new AjaxOptions { HttpMethod = "GET", UpdateTargetId = "modal", OnSuccess = "showModal()"})
This code loads my form (partial view) into a div and opens it as a modal window. In the form submit ActionResult I just use the default ModelState object to validate it, and in case of an error I return the same partial view containing model errors. This works fine except for the following situation: when the model contains no errors I want to auto-close the modal window. I tried the following:
#using (Ajax.BeginForm("Save", "Home", new AjaxOptions {HttpMethod = "POST", UpdateTargetId = "modal", OnSuccess = "hideModal(); alert('Saved');"}))
However, when the model contains errors the Ajax call is still valid, so OnSuccess will be called. I tried to solve this by sending an error HttpStatusCode in the partial view, but then the div is not updated with the new html.
I think the only solution is sending a partial view containing javascript code that closes the modal window when the model contains no errors, but this solution is not very neat in my opinion. Any other ideas?
I just had to do the same thing today. The solution I came up with was to return a JsonResult with a property set to true when the action succeeded. In the OnSuccess callback of the AjaxOptions I checked for the property and closed my modal window.
Controller Method
[HttpPost]
public ActionResult Hold(JobStatusNoteViewModel model)
{
if (ModelState.IsValid)
{
//do work
return Json(new {success = true});
}
return PartialView("JobStatusNote", model);
}
PartialView
<% using (Ajax.BeginForm(new AjaxOptions { UpdateTargetId = "JobStatusForm", OnSuccess = "closePopUp" })) { %>
<div id="JobStatusForm">
<!-- Form -->
</div>
<% } %>
<script>
function closePopUp(data) {
if (data.success) {
//close popup
}
}
</script>

MVC 2.0 Ajax: auto-submit on dropdown list causes normal postback

I am trying to add Ajax functionality to my MVC application. I want a form to post back asynchronously. Here's the form code:
using (Ajax.BeginForm("SetInterviewee", "Date", routeValues, new AjaxOptions { UpdateTargetId = "divInterviewee" }))
and I want it to automatically post back when a dropdown list selected value changes:
<%= Html.DropDownList("interviewees", Model.interviewees.intervieweeLists.intervieweesList, "-- select employee --", new { #class = "ddltext", style = "width: 200px", onchange = "this.form.submit();" })%>
However, when I try this out, the program posts back normally, not a partial postback as I was expecting. Here's what I think the problem is: onchange = "this.form.submit();" in the dropdown list.
I think that this somehow causes a normal postback instead of the asynchronous postback.
Here's what MVC generates for HTML for the form tag:
<form action="/SetInterviewee/2011-1-26/2011-1/visit" method="post" onclick="Sys.Mvc.AsyncForm.handleClick(this, new Sys.UI.DomEvent(event));" onsubmit="Sys.Mvc.AsyncForm.handleSubmit(this, new Sys.UI.DomEvent(event), { insertionMode: Sys.Mvc.InsertionMode.replace, updateTargetId: 'divInterviewee' });">
I think that with "this.form.submit()" the "onsubmit" event handler is not being called. The thing is, I don't understand why. Wouldn't "onsubmit" catch any event that submits the form?
UPDATE: I went to jquery, thusly:
$(function () {
$('#interviewees').change(function () {
var form = $('#intervieweeForm');
$.ajax({
url: form.attr('action'),
type: form.attr('method'),
data: form.serialize(),
success: function (result) {
$('#selectedInterviewee').val(result);
}
});
});
});
This is causing many problems, among them:
-- It still does not seem to do an asyncrhonous postback. In my controller action method, I have the following code: "if (Request.IsAjaxRequest())" which returns false.
-- I can't seem to do model binding any more. My route looks like :
http://localhost:1986/Interviews/2011-2-25/2011-2/visit
but the route that apparently ends up being sent is
http://localhost:1986/SetInterviewee/2011-2-25/2011-2?
Count=5&Keys=System.Collections.Generic.Dictionary`2+KeyCollection
[System.String,System.Object]
&Values=System.Collections.Generic.Dictionary`2+ValueCollection
[System.String,System.Object]
causing the model binding not to work -- "visit" is supposed to be a "mode" parameter, but it's not there so "mode" defaults to "phone", which upsets the whole applecart.
It is the serialize command that is causing this? I don't understand why it would append it to the querystring when the method is POST.
There are other things -- among them, the fact that my action must return a ViewResult, so how can I possibly just return a string, which is all I need using ajax ... but I will defer that concern until I get the routing/binding thing straightened out!
UPDATE: "SetInterviewee" is indeed the correct route to post to, but the routeValues parameter should copy the route values from the current view -- I would think. Here's the code for the form:
RouteValueDictionary routeValues = ViewContext.RouteData.Values;
using (Html.BeginForm("SetInterviewee", "Date", routeValues, FormMethod.Post, new { id = "intervieweeForm" }))
So I know this is quite an old question, but I've been messing around with a similar issue and seem to come to a workaround that might prove useful in the future.
Inside your form, add a submit button. Something like:
<input type="submit" name="submit" value="save" style="display: none;" />
Make sure that you have specified the name attribute as it seems to matter in this case. Here is the code I have an it is currently working with full model binding:
<% using (Ajax.BeginForm("SaveStatus", "Finding", new { FindingId = Model.FindingId },
new AjaxOptions {
HttpMethod = "Post",
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "StatusWindow",
OnBegin = "function(){ jQuery('#SaveStatusForm').block({ Message: 'Saving' }); }",
OnComplete = "function(){ jQuery('#SaveStatusForm').unblock(); }",
OnFailure = "HandleMSAjaxFail",
}, new { id = "SaveStatusForm" })) { %>
<div>
<%: Html.DropDownListFor(Status => Status.SelectedTagId, Model.AvailableStatuses, null, new Dictionary<string, object> { { "onchange", "jQuery('#SaveStatusForm').submit();" } })%>
<input type="submit" name="submit" value="save" style="display: none;" />
</div>
<% } %>
Granted this is my code and not tied to your example, but you can get the idea from what is going on. Originally I had the dropdownlist just doing a submit and when it fired I was getting all sorts of quirky responses - including a full synchronous postback. When I added the submit button, the MS ajax code seems to work beautifully. Give it a shot!
I would recommend you to use jquery and get rid of all Ajax.* helpers and MSAjax scripts.
So:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<% using (Html.BeginForm("SetInterviewee", "Date", routeValues, FormMethod.Post, new { id = "myform" })) { %>
...
<% } %>
<%= Html.DropDownList(
"interviewees",
Model.interviewees.intervieweeLists.intervieweesList,
"-- select employee --",
new { id = "interviewees", #class = "ddltext", style = "width: 200px" }
)%>
and then in a separate javascript file:
$(function() {
$('#interviewees').change(function() {
var form = $('#myform');
$.ajax({
url: form.attr('action'),
type: form.attr('method'),
data: form.serialize(),
success: function(result) {
$('#divInterviewee').html(result);
}
});
});
});
Now we have successfully separated HTML markup from javascript. It is unobtrusive javascript.

Resources