Second time partialview not loading to div via from .ajax() in MVC4 - asp.net-mvc

I have issue loading partialview to div second time. I have checked previous posts in SO but non of them really helped me. So I am posting my issue here.
index.cshtml
<div id="DivEmailContainer" style="display:block" class="row">
</div>
_EditEmail.cshtml
<div class="row">
<div class="col-xs-12 col-sm-6 col-md-2 ">
<input type="submit" value="Save" class="btn btn-success width100per" />
</div>
script type="text/javascript">
$(function () {
$("#frmEmail").validate({
rules: {
...
submitHandler: function (form) {
$.ajax({
url: 'PostEditEmail',
type: 'Post',
data: $(form).serialize(),
success: function (result) {
alert("In success");
$('#DivEmailContainer').html(result);
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.responseText);
alert(thrownError);
},
complete: function (xhr, textStatus) {
alert(xhr.responseText);
alert(textStatus);
}
});
}
});
controller
public PartialViewResult PostEditEmail(string actiontype, FormCollection col)
{
var communicationLocation = string.Empty;
....
return PartialView("_EditEmail", memberemail);
}
First time partialview loading into DivEmailContainer to error. If submit again partialview loading full post back. not even it is calling submitHandler.
Only thing I observed is 1st time submit <form post was /ContactInformation/GetEditEmailbut when I submit second time <form post was /ContactInformation/PostEditEmail.
What could be wrong?
update
second time Forloop scriptblock loading. May be it is issue with Forloop?
#using (Html.BeginScriptContext())
{
Html.AddScriptBlock(
update
issue with forloop htmlhelper, not with ajax. secondtime script is not loading. #Russ Cam can help on this.

from my experience putting script in a partial leads to very inconsistent results. expecially with the script being inserted into the middle of the page. I would highly recommend that you pull your script from the partial and put it on the main page. Since the partial is loaded after the page load you will need to tie the script to the partial one of 2 ways.
1. tie the events to the document
$(document).on('click', '.targetClass', function(){
//do stuff
});
for example to put an id on your input and change it to a button
<input type="button" value="Save" id="btnSave" class="btn btn-success width100per" />
your click event would then be
$(document).on('click', '#btnSave', function(){
//your ajax call here
});
being tied to the document this click event would fire even though the input is inserted into the document after load
put the script in a function that is called after the partial is loaded
change your
$(function () {
to
function partialScript(){
and call this function after the partial is loaded
$('#DivEmailContainer').html(result);
partialScript();

Try to load partial view like this
$("#DivEmailContainer").load('#Url.Action('ActionName', 'ControllerName')', function () {
//Perform some operation if you want after load.
});

Related

Using jquery to check if POST is successful

I am trying to write jquery function that will pop up and say Post was successful! and if not, Post was not successful! How could I use a try catch with inputting some jquery?
#using (Html.BeginForm("Admin", "Home", "POST"))
{
<div class="well">
<section>
<br>
<span style="font-weight:bold">Text File Destination:   </span>
<input type="text" name="txt_file_dest" value="#ViewBag.GetTextPath">
<span style="color:black">   Example:</span><span style="color:blue"> \\invincible\\chemistry$\\</span>
<br>
<br>
<span style="font-weight:bold">SQL Connection String:</span>
<input type="text" name="sql_Connection" value="#ViewBag.GetSqlConnection">
<span style="color:black">   Example:</span> <span style="color:blue"> Server=-</span>
<br>
<br>
<button class="btn btn-success" type="submit" >Save Changes</button>
</section>
</div>
}
So I figured out my answer. Just for future reference to anybody that tries this, below is what I did. I placed it above #using (Html.BeginForm("Admin", "Home", "POST")). #Andrew I did try yours, but I could not get it to work. Thanks to everyone for tyring to help me.
<script language="javascript" type="text/javascript">
$(function() {
$("form").submit(function(e) {
$.post($(this).attr("action"), // url
$(this).serialize(), // data
function (data) { //success callback function
alert("Edit successful");
}).error(function () {
alert('failure');
});
e.preventDefault();
});
});
</script>
You'll want to change your HtmlHelper BeginForm declaration slightly, so that an id attribute will be rendered with the element, like this:
#using (Html.BeginForm("Admin", "Home", FormMethod.Post, new { id = "well-form" }))
Now you can add a script above the declaration which traps-and-submits the form and handles the response (success or error).
<script>
$(function() {
// Find the form with id='well-form'
$('#well-form').submit(function() {
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
success: function(result) {
alert('Post was successful!');
},
error: function(result) {
alert('Post was not successful!');
}
});
// return false to cancel the form post
// since javascript will perform it with ajax
return false;
});
});
</script>
$.ajax({
url: 'post.html',
success: function(){
alert('success');
},
error: function(){
alert('failure');
}
});
Compounding to Sonu's answer, I have found similar questions regarding this hard to accomplish as the HTML form submit has no callback and it seems that it is recommended to use ajax() when you want a postback confirmation of your form submission.
Please see this Stackoverflow Link.
Could you use the Ajax Events? such as $.ajaxSuccess
http://api.jquery.com/category/ajax/global-ajax-event-handlers/

two submit buttons on a form

lets say I have a set of establishments, each establishments know who his father is and a establishment can have many childs. now I created a set of cascading dropdowns for this problem so on the first whe find the ones that have no father ( tier 0 if you might), once the user selects an item the list on the second list its children are loaded ( if it has any children) and so on until tier 3, heres my code:
Index.cshtml:
#model WebUI.Controllers.IndexViewModel
<script src="#Url.Content("~/Scripts/jquery-1.7.1.min.js")" type="text/javascript"> </script>
<script src="#Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")" type="text/javascript"></script>
#Html.Partial("ParentEstablishments",Model)
<div id="FirstHeritage">#Html.Partial("FirstHeritageChildren",Model)</div>
<div id="SecondHeritage">#Html.Partial("SecondHeritageChildren",Model)</div>
Each partial view has an ajax form like the following:
#model WebUI.Controllers.IndexViewModel
#using (Ajax.BeginForm("SelectParent","Ticket",new AjaxOptions{UpdateTargetId="FirstHeritage"}))
{
<fieldset>
<legend>Entidad departamental</legend>
#Html.DropDownListFor(
m => m.SelectedParentId ,
new SelectList( Model.AvailableParents , "EstablishmentId" , "Name" ) ,
"[Por favor seleccione una entidad departamental]"
)
<input type="submit" value="Select" />
</fieldset>
}
so what i want to create is a submit button that lets the user tell me hes selected the entity he needs and to call a method on my controller where i check every id for a value, i tried to put the partial views inside a form but every submit button of the ajax forms calls the method of the form i create, how can i make a button without interfering with the ajax forms?
Modify the Button like below.
<input type="button" value="Select" class="btnSubmit" />
Mofify the Form Tag as mentioned below
#using (Ajax.BeginForm("SelectParent","Ticket", FormMethod.Post,
new { id = "myForm" }))
{
}
Modify the Div as mentioned below. Add an attribute which will have value corresponding to it's Controller's Action method.
<div id="FirstHeritage" attr-Url="#Url.Action("ActionName", "ControllerName",
new { area = "AreaName" })"></div>
Now in Jquery. Follow below steps.
Load Partial View
Fetch the Div Attribute Value
Use On for the Button event.
Ajax Request
JQuery
$(document).ready(function () {
var FirstHeritage = $('#FirstHeritage');
var url = FirstHeritage.attr('attr-Url');
FirstHeritage.load(url, function () {
var $form = $('#myForm');
$.validator.unobtrusive.parse($form);
$(document).on('click', '.btnSubmit', function () {
if ($form.valid()) {
$.ajax({
url: Url,
async: true,
type: 'POST',
beforeSend: function (xhr, opts) {
},
contentType: 'application/json; charset=utf-8',
complete: function () { },
success: function (data) {
$form.html(data);
$form.removeData('validator');
$form.removeData('unobtrusiveValidation');
$.validator.unobtrusive.parse($form);
}
});
}
});
});
});
Hope this will help you.
You can't, essentially. The script that makes the AJAX form an AJAX form binds to the submit event, so any submit will be caught.
Remember all the HTML helpers and controls in ASP.NET are there to cover common scenarios and make your life easier when you're actually in a common scenario. The more "custom" your code gets (such as a second submit button that will do a regular POST instead of an AJAX POST), the more work you need to do (and the less you should be using the builtin helpers and controls).
Just create a regular form (Html.BeginForm), add your two submit buttons, and then attach a click event on the AJAX version, and then send the POST as AJAX yourself.

How to switch between view and edit views

I have action method like this:
[ChildActionOnly]
public ActionResult NewUserLanguage()
{
...
return View(model);
}
This view have one simple form on it and a list of partial views:
<ul id="userLanguagesListBox">
#foreach (var l in Model.UserLanguages)
{
<li>
#{Html.RenderPartial("UserLanguageBox", l);}
</li>
}
...
This partial view looks like this:
...
#using (Html.BeginForm("EditUserLanguage", "UserLanguage", FormMethod.Post, new { id = "editUserLanagegeForm" }))
{
<ul>
<li><h3>#Model.Language.Name</h3></li>
<li>#Model.LanguageLevel.Name</li>
<li>
#Html.HiddenFor(x=>x.UserLanguageId)
<button class="editButton">Edit</button>
</li>
</ul>
}
What I am trying to do is when user click on edit button in any of the partials I want to switch it with another view EditUserLanguage.
I have tried something like this:
$(function () {
$('#editUserLanagegeForm').submit(function (e) {
alert('ss');
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
success: function (result) {
$("#" + e.target).closest("div").append(result);
}
});
return false;
});
});
But this function is never called by any of edit buttons.
"The submit event is sent to an element when the user is attempting to submit a form. It can only be attached to elements. Forms can be submitted either by clicking an explicit <input type="submit">, <input type="image">, or <button type="submit">, or by pressing Enter when certain form elements have focus."
-From http://api.jquery.com/submit/
What this means to you is that you need your button to have a type of submit for the submit event to trigger, but I don't think that's the one you're thinking of. Try using .click() instead.

How do I get my success message to show after ajax submitting form in Jquery ui-tab

I have form on a jQuery ui-tab, which loads data onto a list displayed on the same ui-tab. I have managed to get the data loaded, and the display to return to same tab for a further item to be entered. However depending on the sort order of the list the new item is not always visually obvious, I want to fade in a message, but I can't get it to work along with returning to the same tab without a manual page refresh.
I have attached both the scripts I am trying to use.
Script A
<script> // this one loads data perfectly but no success message appears
$(document).ready(function() {
$("#addtodoitem").live( 'submit' , function(evt) {
evt.preventDefault();
$.ajax({
type: $(this).attr('method'),
url: $(this).attr('action'),
data: $(this).serialize(),
success: function(data) {
$('.ui-tabs-panel:visible').html(data);
$('.itemadded').fadeIn(1000).delay(4000).fadeOut(1000);
};
});
});
});
Script B
<script> //this one shows the message and loads the data, but it also loads another
//copy of ui-tabs overlapping the original
$(document).ready(function() {
$('#addtodoitem').ajaxForm(function(data) {
$('.ui-tabs-panel:visible').html(data);
$(".itemadded").fadeIn(1000).delay(4000).fadeOut(1000);
}); return false;
});
HTML
<div id="tabs_5" class="tabs">
<h2 id="todo5" class="tablecaption">Add To-do</h2>
<p>To raise a new issue please enter the description of the issue below.</p>
<form id="addtodoitem" class="todo" method="post" action="todo_do.php?do=<?=$todo_do != '' ? "edit&to_id={$_GET['to_id']}" : 'add'?>&pub=1&site_ref=NA">
<input type="hidden" value="0" name="status" id="status">
<textarea name="todo" id="todo" placeholder="To raise a new issue, please type the details of the issue here"><?=$todo_free_text?></textarea> <br />
<input type="submit" value="Submit" class="button" />
</form>
<h2 class="tablecaption itemadded">Thank you, your item has been added to the list.</h2>
I got to a satisfactory solution by using a separate refresh link button and php page to cause the refresh after posting so the script is so:
<script type="text/javascript">
$(document).ready(function(){
$('#addtodo').click(function(e){
e.preventDefault();
if($('#todo').val()!="")
{
$.ajax({
type: 'POST',
url: 'todo_do.php',
data: { 'status': $('#status').val(),
'todo': $('#todo').val()
},
success: function(data){
$('.itemadded').slideDown(500).delay(2000).fadeOut(500);
$('.refreshtodo').slideDown(500);
$('#addtodoitem')[0].reset();
$('#tabs > ul').tabs({selected: 5 });
}
});
}
else{$('.nothing').slideDown(500).delay(1000).fadeOut(500)}
});
});
and the extra php page just contains
<?
header("Location: resident.php#tabs_5");
?>

How to make ajax postback in form with list of check boxes

I dynamically draw checkboxes in my form:
#using (Html.BeginForm("Action", "Controller", FormMethod.Post, new { id="itemsList"}))
{
foreach (var lt in Model.MyList)
{
<li>
<label id="label">
<input value="#lt.itemId" type="checkbox" />
#lt.Title</label>
</li>
}
}
JQuery function:
$(document).ready(function () {
$('#itemsList').ajaxForm({
success: Saved,
error: HandleError
});
});
...
But my action is not fired. Am I doing something wrong here? I am expecting that when I check checkbox make server call.
I am expecting that when I check checkbox make server call.
You should not expect that unless you've written handler for checkbox change
$(document).ready(function () {
$('#itemsList').ajaxForm({
success: Saved,
error: HandleError
});
$(':checkbox').change(function(){
$('#itemsList').submit();
});
});
ajaxForm will intercept submissions and send them via ajax. But you need to trigger a submit for the ajax call to kick in.
Try adding:
$('input[#type="checkbox"]').click(function(){ $('#itemsList').submit(); }
You may want to refine the checkbox selector to something more specific...

Resources