Using Fancybox with ASP.NET MVC Ajax - asp.net-mvc-3

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.

Related

Ajax.Beginform doesn`t trigger onsuccess method in javascript

I`m trying to send a form in mvc with Ajax.beginform and execute on success function. The function is stated in the form and created in the scripts section. However, the function is not fired after the post is submitted.
The view is partial view and is inserted in Index page.
The method which the form calls in the controller is HttpPost and returns the view again which causes the index page to load again.( I suspect here is the problem)
Basically what im trying to achieve is to show a div in my index page(main) saying successfully record edited.
Also, in my bundle config I have the jquery val & the jquery.validate.unobtrusive.js loaded and in the web.config I added in appconfig
What could be wrong? Here is my code.
[HttpPost]
public async Task<ActionResult> EditPostedJob(JobPost job, string dt)
{
using (var context = new ApplicationDbContext())
{
var post = (from p in context.jobPosts where p.JobPostId == job.JobPostId select p).First();
post.AboutJob = job.AboutJob;
post.Headline = job.Headline;
post.JobAddress = job.JobAddress;
post.JobCity = job.JobCity;
post.JobPostCode = job.JobPostCode;
await context.SaveChangesAsync();
//return Json(post,JsonRequestBehavior.AllowGet);
return RedirectToAction("Index", "Manage");
}
}
in my main view I have this message
<div id="success-edited-job" class="alert alert-success">
<strong>Success!</strong> the posted job has been successfully edited.
</div>
and also I have the js which hides this when page is loaded. And then I add the partial view with the form and there is set the success-edited-job div to show when post is successful but it return again the index view and the div is hidden again.
this is my partialview form
#using (Ajax.BeginForm("EditPostedJob", FormMethod.Post, new AjaxOptions() { OnSuccess = "JobEditedSuccessfully", OnFailure = "JobEditFail",HttpMethod="POST" }))
and the js
<script type="text/javascript">
function JobEditedSuccessfully(data) {
alert("lol");
}
function JobEditFail(error) {
console.error(error);
}
</script>

mvc3 partialview target by div tag

I have an issue with a partialview, for some reason when I do a Post on it; it gives me another copy of my form; how can I make that behavior go away . This is what that partialview looks like:
// this is all inside my partialview
<div style=" float:left;">
#using (Ajax.BeginForm("posting", "post", null, new AjaxOptions
{
UpdateTargetId = "glober",
InsertionMode = InsertionMode.Replace,
HttpMethod = "POST"
}))
{
// taken out
}
</div>
<div id="glober">
#foreach (var item in Model.Mymodel)
{
}
</div>
as you can see this is a POST and I only want to update the part with the id of "glober" which it does but for some reason when I do the post it also gives me a second copy of the form elements. If inside my ajax form I have 1 textbox called firstname then after submitting it I get 2 textboxes that says firstname, any help would be great.
Part of my controller is this were i call out the partial
var iefeeds = sqlConnection.Query<thread>("Select * from postings").ToList();
return PartialView("_mypartial");
I think you have returned View rather than PartialView in the controller. So you'll see 2 pages overlapping in response of ajax Post.

ajax.actionlink post form not showing ckeditor

After Using the Ajax.ActionLink As
#Ajax.ActionLink("Edit", "AddEdit", new { #id = id, #recId = item.EncyclopediaID }, new AjaxOptions { InsertionMode = InsertionMode.Replace, UpdateTargetId = "listForm" }, new { #class = "edit_icon", #title = "edit this item" })
And When Controller Go to AddEdit Page There i have Uploaded the File and want to show the Ckeditor.
So i use
#using (Html.BeginForm("AddEdit", "Encyclopedia", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
/////////other code//////////////////
#Html.EditorFor(model => model.Description,"CKEditor")
}
Now if i use to show the #Html.ActionLink instead of #Ajax.Actionlink Ckeditor Shows perfectly and in Ajax call it showed like a textarea.
Please Help.
this happens because resource files required for ckeditor to work correctly (eg: css , javascript) cannot be downloaded with an ajax call.
try referencing the required resource files in layout view page and try again.
Edit :
maybe you have placed integration code in document.ready function, thus after ajax request completed and you markup changed, the new markup (eg:your new input element) is not configured as ckeditor input.so try calling ckeditor integration code after ajax success.

Validate only ajax loaded partial view

I have a form with some controls. There is a button on the form which loads a partial view. Inside the partial view, there are two required field textboxes along with a button. And when its clicked, I need to display error messages only for textboxes which are inside the partial view, but not for the fields in the actual form. And when I click form's submit button, all error messages must show up.
After partial view is loaded, I am re-initializing the validation plugin as below.
$('#test').removeData("validator");
$.validator.unobtrusive.parse('#test');
I tried using validation attribute described in below thread but its not working. Maybe it works for normally loaded views.
ASP.NET MVC Validation Groups?
However, I can validate individually by calling textbox1.valid() and textbox2.valid(). But I think I am missing standard way of doing it. Any help is appreciated.
you can do this by submitting your partial view using Ajax.BeginForm()
//In Partail View
#model SomeModel
#using (Ajax.BeginForm("SomeActionName", new AjaxOptions { HttpMethod = "POST", UpdateTargetId = "targetId"}))
{
#Html.EditorFor(mode=>model.FirstText)
#Html.EditorFor(mode=>model.SecText)
<input type="submit" value="save">
}
//In Controller
public ActionResult SomeAction(SomeModel model)
{
return PartaiulView(model);
}
here you can validate your Partial View
NOTE: when you submit you form using Ajax.BeginForm you must specify "UpdateTargetId" where your result will be appear on View.
//In View
<div id="targetId">
#Html.Partail("PartialView")
</div>
OR if you want to Redirect to another action if your model is valid then modified your action
public ActionResult SomeAction(SomeModel model)
{
if(ModelState.IsValid)
{
return Json(new {redirect = #Url.Action("SomeAction","SomeController")})
}
return PartaiulView(model);
}
then in partail view you can invoke OnSuccess method of Ajax.BeginForm
#using (Ajax.BeginForm("SomeActionName", new AjaxOptions { HttpMethod = "POST", UpdateTargetId = "targetId",OnSuccess="success"}))
{
}
<script type="text/javascript">
function success(data)
{
if(data.redirect)
{
windows.location = data;
}
}
</script>
check both way which one is suitable to you.

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>

Resources