MVC AJAX post sending updated model data - javascript

I'm trying to send a post request to the Action with the Model data after the value of some of it's properties is changed :
#{
JsonSerializerSettings jss = new JsonSerializerSettings {
ReferenceLoopHandling = ReferenceLoopHandling.Ignore };
}
<div id="contents">
<!--Lead Stage-->
#if (Model.LeadStagesNav != null)
{
for (int i = 0; i < Model.LeadStagesNav.Count; i++)
{
#Html.HiddenFor(a => a.LeadStagesNav[i].PermissionId)
<div class="form-group" style="margin-bottom:10px">
#Html.Label("Lead Stage", new { #class = "col-md-2" })
<div style="display:inline-block;position:relative">
#Html.DropDownListFor(model => model.LeadStagesNav[i].Name, null, new { #class = "form-control", #style = "width:200px", onchange = "ChangeValue()" })
</div>
#if (ViewData["LeadStagesNav[" + i + "].LeadStatus"] != null)
{
<!--Lead Status-->
#Html.Label("Lead Status", new { #style = "margin-left:15px;margin-right:15px" })
<div style="display:inline-block;position:relative">
#Html.DropDownListFor(model => model.LeadStagesNav[i].LeadStatus, null, new { #class = "form-control", #style = "width:200px", onchange = "ChangeValue()" })
</div>
if (ViewData["LeadStagesNav[" + i + "].LeadSubStatus"] != null)
{
#Html.Label("Lead Sub Status", new { #style = "margin-left:15px;margin-right:15px" })
<div style="display:inline-block;position:relative">
<!--Lead Sub Status-->
#Html.DropDownListFor(model => model.LeadStagesNav[i].LeadSubStatus, null, new { #class = "form-control", #style = "width:200px" })
</div>
}
}
</div>
<!--Delete Button-->
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Delete Lead Stage"
onclick="document.getElementById('index').value = #i"
name="submit" class="btn btn-default" />
<input type="hidden" id="index" name="index" />
</div>
</div>
}
}
</div>
<script type="text/javascript">
window.ChangeValue = function () {
var model = #Html.Raw(JsonConvert.SerializeObject(Model, Formatting.Indented, jss));
$.ajax({
method: "POST",
url: "/CmsPermissions/Edit",
data: { permission: model },
success: function (data) {
$("#contents").html(data);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(errorThrown);
}
});
};
the thing is the The problem is that I get the old model data
posted to the Action instead of the
new data after the dropdown selected value has changed,
Anyone has any idea ?

that is because you are passing the old model as data
var model = #Html.Raw(JsonConvert.SerializeObject(Model, Formatting.Indented, jss));
you need to serialize your form and pass it an example is
function SubmitForm() {
var data = $("#YourFormID").serialize();
var url = "/YourURL/ACtion"
var form = $('#policyForm')[0]
var formdata = false;
if (window.FormData) {
formdata = new FormData(form);
}
return $.ajax({
url: url,
type: 'POST',
dataType: 'json',
data: formdata ? formdata : data,
cache: false,
contentType: false,
enctype: 'multipart/form-data',
processData: false,
error: function () {
$('#imgLoadingForPortal').modal('hide');
Lobibox.notify('error', {
size: 'mini',
rounded: true,
delay: false,
position: 'center top', //or 'center bottom'
msg: 'Something went wrong..please try again later',
sound: false,
delay: 5000,
});
}
})
}

Related

Ajax call working only for first row of the table and not working for next rows

In my view I'm displaying a table and in table I strongly typed dropdown list and as you change selected item it calls getPrice(int product_id) function through ajax call and returns price of selected item but it only works for 1st row.
HTML
<tr class="tr_clone" id="1">
<td>
#Html.DropDownListFor(model => model.product_id, ViewBag.ProductList as SelectList, "--select product--", new { #class = "form-control sel"}
</td>
<td class="product_price" id="product_price" style="text-align: center; font-size: 16px;">#Html.DisplayFor(model => model.product_price, "", "") </td></tr>
<tr class="tr_clone1" id="2">
<td>
#Html.DropDownListFor(model => model.product_id, ViewBag.ProductList as SelectList, "--select product--", new { #class = "form-control sel"})
</td>
<td class="product_price" id="product_price1" style="text-align: center; font-size: 16px;">#Html.DisplayFor(model => model.product_price, "", "")</td></tr>
Ajax call
$(function () {
$('#product_id').change(function () {
$.ajax({
type: "POST",
url: "/Home/GetPrice",
datatype: "Json",
data: { product_id: $('#product_id').val() },
success: function (data) {
document.getElementById('product_price').innerHTML = data;
multiply();
},
error: function (data = 0) {
document.getElementById('product_price').innerText = 0;
multiply();
}
});
});
});
html
#Html.DropDownListFor(model => model.product_id, ViewBag.ProductList as SelectList, "--select product--", new { #class = "form-control sel", #onchange = "gg(this)" })
ajax call
<script>
function gg(x) {
$.ajax({
type: "POST",
url: "/Home/GetPrice // GetPrice is name of actionmathod of controller",
datatype: "Json",
data: { product_id: $(x).val() },
success: function (data) {
//your code here
},
error: function () {
// your code here
}
});
}
</script>
You need to set 2 different ids for each dropdown.
#Html.DropDownListFor(model => model.product_id, ViewBag.ProductList as SelectList, "--select product--", new { #id = "ddl_product_id_1", #class = "form-control sel"}
#Html.DropDownListFor(model => model.product_id, ViewBag.ProductList as SelectList, "--select product--", new { #id = "ddl_product_id_2", #class = "form-control sel"})
And write change event of individual that dropdown id.
Since you are selecting 2 different products, you model should have 2 id properties - product1_id and product2_id and 2 price properties - product1_price and product2_price
So fix your view accordingly
<tr class="tr_clone" id="1">
<td>
#Html.DropDownListFor(model => model.product2_id, ViewBag.ProductList as SelectList, "--select product--", new { #class = "form-control sel"}
</td>
<td class="product_price" id="product_price" style="text-align: center; font-size: 16px;">#Html.DisplayFor(model => model.product1_price, "", "") </td></tr>
<tr class="tr_clone1" id="2">
<td>
#Html.DropDownListFor(model => model.product2_id, ViewBag.ProductList as SelectList, "--select product--", new { #class = "form-control sel"})
</td>
<td class="product_price" id="product2_price" style="text-align: center; font-size: 16px;">#Html.DisplayFor(model => model.product2_price, "", "")</td></tr>
and you should 2 separate on change too
$(function () {
$('#product1_id').change(function () {
$.ajax({
type: "POST",
url: "/Home/GetPrice",
datatype: "Json",
data: { product_id: $('#product1_id').val() },
success: function (data) {
document.getElementById('product1_price').innerHTML = data;
multiply();
},
error: function (data = 0) {
document.getElementById('product1_price').innerText = 0;
multiply();
}
});
});
$('#product2_id').change(function () {
$.ajax({
type: "POST",
url: "/Home/GetPrice",
datatype: "Json",
data: { product_id: $('#product2_id').val() },
success: function (data) {
document.getElementById('product2_price').innerHTML = data;
multiply();
},
error: function (data = 0) {
document.getElementById('product2_price').innerText = 0;
multiply();
}
});
});
});

how to disable button during ajax request

so I have a razor form and I want to disable a button during ajax request.
Also I want to be able to send only one request to controller - (disable any flood attempt)
This is my html:
<div class="row">
<div class="col-md-8 col-md-offset-2">
#using (Html.BeginForm(null, null, FormMethod.Post, new { id = "contactForm" }))
{
<div class="clearfix">
<div class="cf-left-col">
<div class="form-group required">
#Html.TextBoxFor(m => m.CheckInCheckOutDate, new { #class = "form-control input-md round", #required = "required", #autocomplete = "off", #id = "input-id", #placeholder = Resources.Resources.CheckInCheckOutPlaceholderKey })
<div>
#Html.ValidationMessageFor(m => m.CheckInCheckOutDate, null, new { #class = "text-danger" })
</div>
</div>
<div class="form-group required">
#Html.TextBoxFor(m => m.Name, new { #class = "form-control input-md round", #required = "required", #placeholder = "Name" })
<div>
#Html.ValidationMessageFor(m => m.Name, null, new { #class = "text-danger" })
</div>
</div>
<div class="form-group required">
#Html.TextBoxFor(m => m.MobilePhone, new { #class = "form-control input-md round mobile", #required = "required", #placeholder = "Mobile phone" })
<div>
#Html.ValidationMessageFor(m => m.MobilePhone, null, new { #class = "text-danger" })
</div>
</div>
<div class="form-group required">
#Html.TextBoxFor(m => m.EMail, new { #class = "form-control input-md round", #required = "required", #placeholder = "E-Mail" })
<div>
#Html.ValidationMessageFor(m => m.EMail, null, new { #class = "text-danger" })
</div>
</div>
<div class="form-group required">
#Html.TextBoxFor(m => m.AdultsNumber, new { #class = "form-control input-md round person", #required = "required", #placeholder = "Guests" })
<div>
#Html.ValidationMessageFor(m => m.AdultsNumber, null, new { #class = "text-danger" })
</div>
</div>
<div class="form-group required">
#Html.TextBoxFor(m => m.ChildrenNumber, new { #class = "form-control input-md round person", #placeholder = "Children" })
</div>
</div>
<div class="cf-right-col">
<div class="form-group required">
#Html.TextAreaFor(m => m.MessageBody, new { #class = "form-control input-md round", #rows = 10, #placeholder = "Message" })
<div>
#Html.ValidationMessageFor(m => m.MessageBody, null, new { #class = "text-danger" })
</div>
</div>
#*localhost*#
#*<div class="g-recaptcha" data-sitekey="6LdKaUAUAAAAAMi2MkpRBxJYnmqWJmnJmF22RsRF1"></div>*#
</div>
</div>
#Html.HiddenFor(m => m.MobilePrefixCountry)
#Html.HiddenFor(m => m.ApartmentName)
#Html.HiddenFor(m => m.NumberOfNights)
<br />
<div class="align-left pt-10">
<div class="form-group">
<input id="submitBtn" class="btn btn-default" type="submit" value="Send Message" />
</div>
</div>
<div id="successAlert" class="alert alert-success collapse">
×
<strong>Success!</strong> You have successfully send email. Our staff will respond in shortest amount of time.
</div>
<div id="errorAlert" class="alert alert-danger collapse">
×
<strong>Sending failed!</strong> Please fill all neccessery fields and try again.
</div>
}
</div>
</div>
I have this js:
$("#contactForm").submit(function (e) {
var form = $(this);
$('#submitBtn').attr("disabled", true);
$("#submitBtn").attr("value", 'Sending...');
//$.ajax({
// type: "POST",
// async:false,
// url: "/Home/SendEmail",
// data: form.serialize(), // serializes the form's elements.
// success: function (data) {
// if (data == "True") {
// $('#successAlert').show('fade')
// .delay(9000)
// .fadeOut(function () {
// $(this).remove();
// });
// }
// else if (data == "False") {
// $('#errorAlert').show('fade')
// .delay(6000)
// .fadeOut(function () {
// $(this).remove();
// });
// }
// }
//});
setTimeout(function () {
$('#submitBtn').attr("disabled", false);
$("#submitBtn").attr("value", 'Send Message');
}, 3000);
e.preventDefault();
});
This works just fine, but when I uncomment ajax section, I am not able to see transition of toggling button disable/enable. I've put async:false.
UPDATED (still not working):
$("#contactForm").submit(function (e) {
var form = $(this);
$('#submitBtn').attr("disabled", true);
$("#submitBtn").attr("value", 'Sending...');
$.ajax({
type: "POST",
async: false,
url: "/Home/SendEmail",
data: form.serialize(), // serializes the form's elements.
success: function (data) {
if (data == "True") {
$('#successAlert').show('fade')
.delay(9000)
.fadeOut(function () {
$(this).remove();
});
}
else if (data == "False") {
$('#errorAlert').show('fade')
.delay(6000)
.fadeOut(function () {
$(this).remove();
});
}
$('#submitBtn').attr("disabled", false);
$("#submitBtn").attr("value", 'Send Message');
},
error: function () {
$('#submitBtn').attr("disabled", false);
$("#submitBtn").attr("value", 'Send Message');
}
});
e.preventDefault();
});
Change async: false to async: true and enable button again in some callback of ajax request. As long as you keep async: false you are blocking main thread and changes for GUI elements will not take effect till function returns.
async from false to true is the only change to #adaptable.services' code.
Place your button enable code inside the ajax success.
This will enable the disabled button after ajax completion.
first make your <input type="submit"> to <button type="submit">Send Message</button>
and then try this..
<script>
$("#contactForm").submit(function (e) {
e.preventDefault();
var form = $(this);
$('#submitBtn').attr("disabled", true);
$("#submitBtn").html('Sending...');
$.ajax({
type: "POST",
async:false,
url: "/Home/SendEmail",
data: form.serialize(), // serializes the form's elements.
success: function (data) {
if (data == "True") {
$('#submitBtn').prop("disabled", false);
$('#submitBtn').html("Send Message");
$('#successAlert').show('fade')
.delay(9000)
.fadeOut(function () {
$(this).remove();
});
}
else if (data == "False") {
$('#submitBtn').prop("disabled", false);
$('#submitBtn').html("Send Message");
$('#errorAlert').show('fade')
.delay(6000)
.fadeOut(function () {
$(this).remove();
});
}
},
error: function () {
$('#submitBtn').prop("disabled", false);
$('#submitBtn').html("Send Message");
}
});
});
</script>
$('#button').attr("disabled", true);
$.ajax({
url: url,
data: data,
type: 'post',
dataType: 'json',
cache: false,
async: true,
complete: function(response){
$('#button').attr("disabled", false);
},
});

jQuery unobstrusive validation fetch server response and display it

I have a form like following:
#using (Html.BeginForm("DoRegister", "User", FormMethod.Post))
{
#Html.AntiForgeryToken()
<div class="inputBox">
#Html.TextBoxFor(m => m.FirstName, new { #class = "form-control", #type = "text", #aria_describedby = "emailHelp" })
<label>First name</label>
#Html.ValidationMessageFor(model => model.FirstName, "", new { #class = "text-danger", #style = "float:right;" })
</div>
<div class="inputBox">
#Html.TextBoxFor(m => m.LastName, new { #class = "form-control", #type = "text", #aria_describedby = "emailHelp" })
<label>Last name</label>
#Html.ValidationMessageFor(model => model.LastName, "", new { #class = "text-danger", #style = "float:right;" })
</div>
<div class="inputBox">
#Html.TextBoxFor(m => m.Email, new { #class = "form-control", #type = "email", #aria_describedby = "emailHelp" })
<label>Email</label>
#Html.ValidationMessageFor(model => model.Email, "", new { #class = "text-danger", #style = "float:right;" })
</div>
<div class="inputBox">
#Html.TextBoxFor(m => m.Password, new { #class = "form-control", #type = "password" })
<label>Password</label>
#Html.ValidationMessageFor(model => model.Password, "", new { #class = "text-danger", #style = "float:right;" })
</div>
<div class="inputBox" style="overflow: hidden;clear: both;height: 80px;">
<div class="g-recaptcha" style="padding-top:15px; float:left;transform:scaleX(1.385) !important;-webkit-transform:scaleX(1.385) !important;transform-origin:0 0;-webkit-transform-origin:0 0;" data-sitekey="somekey"></div>
</div>
<button type="submit" class="btnregister">Create Account</button>
}
For this form I've enabled jQuery unobstrusive validation where I added these script tags:
Bingo, it works like expected! Now I'm just missing the part where I wanna handle the response from the server when the form is submitted...
For example I have tried:
<script>
$(document).ready(function () {
$('form').submit(function (event) {
event.preventDefault();
if ($(this).valid()) {
var formdata = new FormData($(this).get(0));
$.ajax({
url: this.action,
type: this.method,
data: formdata,
processData: false,
contentType: false,
success: function (result) {
// element is div holding the ParticalView
alert("OK!");
}
});
}
return false;
});
});
</script>
In this part:
if ($(this).valid()) {
I'm getting an error:
Uncaught TypeError: $(...).valid is not a function
And these are the scripts that I've included:
<script type="text/javascript" src="~/siteContent/frontpage/js/jquery-3.2.1.min.js"></script>
<script src='#Url.Content("~/siteContent/js/jquery.validate.min.js")'></script>
<script src='#Url.Content("~/siteContent/js/jquery.validate.unobtrusive.js")'></script>
What am I doing wrong here??
Can someone help me out?
Once try js files position change
i) either top of body part
ii) end body part
if you are using Layout multiple time loades jquery-3.2.1.min.js file
first load js file and then put your validate.min.js,jquery.validate.unobtrusive.js
<script type="text/javascript" src="~/siteContent/frontpage/js/jquery-3.2.1.min.js"></script>
<script src='#Url.Content("~/siteContent/js/jquery.validate.min.js")'></script>
<script src='#Url.Content("~/siteContent/js/jquery.validate.unobtrusive.js")'></script>
Put your script here after you have referenced all the scripts.
<script>
$(document).ready(function () {
$('form').submit(function (event) {
event.preventDefault();
if ($(this).valid()) {
var formdata = new FormData($(this).get(0));
$.ajax({
url: this.action,
type: this.method,
data: formdata,
processData: false,
contentType: false,
success: function (result) {
// element is div holding the ParticalView
alert("OK!");
}
});
}
return false;
});
});
</script>
Hope it works :)

Populating Listbox using Jquery and passing values with Model on submit

Nothing is being added to my Listbox
Once i DO get these items added to the listbox, how do I pass it through with my model on submit ?
The values from the Controller ARE being pulled through, as I tested using an alert. What am I missing that is not passing through these values to my listbox?
View:
<div class="form-group form-group-sm">
#Html.Label("Items", new { #class = "control-label" })
#*#Html.ListBoxFor(x => x.SelectedAccountItems, Model.UserItems, new { #class = "form-control", #id = "ddlistaccountitems", #multiple = "multiple" })*#
#Html.ListBox("ItemsDDL", new SelectList(new[] { "" }),new { #class = "form-control", #id = "ddlistaccountitems", #multiple = "multiple" })
</div>
JQUERY:
$("#ddlistcategory").change(function () {
var catItem = $("#ddlistcategory").val();
$("#ddlistaccountitems").empty();
$.ajax({
url: '#Url.Action("GetCategories", "Account")',
dataType: "json",
type: "Post",
data: { "i": catItem },
success: function (data) {
$.each(data, function (key, val) {
//alert(key + " " + val);
$("#ddlistaccountitems").append('<option id="5">5</option>');
})
}
});
});
Controller:
public JsonResult GetCategories(string i)
{
Dictionary<string, string> lstCategories = new Dictionary<string, string>();
lstCategories.Add("1", "Beverages");
lstCategories.Add("2", "Condiments");
lstCategories.Add("3", "Confections");
lstCategories.Add("4", "Dairy Products");
lstCategories.Add("5", "Grains/Cereals");
lstCategories.Add("6", "Meat/Poultry");
lstCategories.Add("7", "Produce");
lstCategories.Add("8", "Seafood");
return Json(lstCategories, JsonRequestBehavior.AllowGet);
}
So - Typical - after posting for help after HOURS of struggling, I get the solution!
My problem was that my ListBox was ACTUALLY called ItemsDDL, so the #id = "ddlistaccountitems" was not recognized.
So I figured out how to pass the values to my model as well:
VIEW:
<div class="form-group form-group-sm">
#Html.Label("Items", new { #class = "control-label" })
#Html.ListBoxFor(x => x.SelectedAccountItems, Model.UserItems, new { #class = "form-control", #id = "ddlistaccountitems", #multiple = "multiple" })
</div>
JQUERY:
$("#ddlistcategory").change(function () {
var catItem = $("#ddlistcategory").val();
$("#ItemsDDL").empty();
$.ajax({
url: '#Url.Action("GetCategories", "Account")',
dataType: "json",
type: "Post",
data: { "i": catItem },
success: function (data) {
$.each(data, function (key, val) {
//alert(key + " " + val);
$("#ddlistaccountitems").append('<option id="' + key + '">' + val + '</option>');
})
}
});
});

Bootbox Dialog with Ajax Callback

I have this button on the UI where the customer will open a modal. The modal will load a partial view retrieved by Ajax.
$('#btnfeedback').on('click', function(e) {
e.preventDefault();
var debateModal;
$.get('#Url.Action("LoadFeedbackModal", "Home")', function() {
}).done(function(info) {
debateModal = bootbox.dialog(
{
message: info,
title: '<span class="fa fa-wechat"></span> Leave Feedback',
closeButton: true
});
debateModal.find('.modal-header').removeClass('modal-header').addClass('modal-header-info');
}).fail(function() {
debateModal = bootbox.alert({ message: "Problem try later", size: 'small' });
});
});
And this is my Controller:
[HttpGet]
public ActionResult LoadFeedbackModal()
{
return PartialView("Partials/_FeedbackModal", new FeedbackVm());
}
[HttpPost]
public ActionResult LoadFeedbackModal(FeedbackVm feedback)
{
try
{
var fb = Mapper.Map<Feedback>(feedback);
Db.Feedbacks.Add(fb);
Db.SaveChanges();
return Json(new { Mensaje = "Thanks for your feedback", Status = true }, JsonRequestBehavior.AllowGet);
}
catch (Exception exception)
{
return Json(new { Mensaje = "HUbo un problema :( Intenta luego", Status = false }, JsonRequestBehavior.AllowGet);
}
}
And this is my partial view:
#model TuGrietaLive.ViewModels.Admin.Index.FeedbackVm
#using (Html.BeginForm("LoadFeedbackModal", "Home", FormMethod.Post))
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<p>
Muchas gracias por tu Feedback. Para nosotros es muy importante.
<small>Si nos dejas tu correo te podemos contestar :)</small></p>
<div class="form-group">
#Html.LabelFor(m => m.FeedbackType, new { #class = "control-label col-md-2 col-xs-12" })
<div class="col-md-10 col-xs-12">
#Html.EnumDropDownListFor(model => model.FeedbackType, "Selecciona una Categoria", new { #class = "form-control", name = "FeedbackType" })
#Html.ValidationMessageFor(model => model.FeedbackType)
</div>
</div>
<div class="form-group">
<label class="control-label col-md-2 col-xs-12">Email <small>(Opcional)</small></label>
<div class="col-md-10 col-xs-12">
#Html.EditorFor(model => model.Email, new { htmlAttributes = new { #class = "form-control"} })
#Html.ValidationMessageFor(model => model.Email, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(m => m.Comment, new { #class = "control-label col-md-2 col-xs-12" })
<div class="col-xs-12 col-md-10 ">
#Html.EditorFor(model => model.Comment, new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.Comment, "", new { #class = "text-danger", rows = 10 })
</div>
</div>
<button type="submit" id="btnsendFeedback" autofocus class="btn btn-block btn-success">
<span class="glyphicon glyphicon-envelope"></span>Enviar
</button>
</div>
}
I can successfully get the view and the modal draws the partial. Now I want to get the response of the server after submitting the form.
How can I get post action message? This code opens a new window with JSON object. I want to capture that and open a modal. This is killing me.
You should change button type of btnsendFeedback in your feedback dialog to button instead of submit:
<button type="button" id="btnsendFeedback" autofocus class="btn btn-block btn-success">
<span class="glyphicon glyphicon-envelope"></span>Enviar
</button>
and handle click event of btnsendFeedback upon receiving dialog content:
$('#btnfeedback').on('click', function (e) {
e.preventDefault();
var debateModal;
$.ajax({
url: '#Url.Action("LoadFeedbackModal", "Home")',
type: 'GET'
}).done(function (info) {
debateModal = bootbox.dialog(
{
message: info,
title: '<span class="fa fa-wechat"></span> Leave Feedback',
closeButton: true
});
debateModal.find('.modal-header').removeClass('modal-header').addClass('modal-header-info');
$('#btnsendFeedback').on('click', function (e) {
$.ajax({
url: '#Url.Action("LoadFeedbackModal")',
type: 'POST',
dataType: 'json'
}).done(function (result) {
console.log(result.Mensaje);
});
});
}).fail(function (xhr, status, error) {
debateModal = bootbox.alert({ message: "Problem try later", size: 'small' });
});
});
To begin, add an ID or class to your form so that we can hook into it's submit event:
#using (Html.BeginForm("LoadFeedbackModal", "Home", FormMethod.Post, new { #id="feedback-form" }))
Then you can use that selector to get the form:
var form = $('#feedback-form');
Alternatively, you could use find() to get the form from the modal:
var form = debateModal.find('form');
Next, add an event handler for the form's submit event:
form.on('submit', function(e){
});
You'll want to cancel the native event, and then use serialize() to prepare your AJAX data:
form.on('submit', function(e){
e.preventDefault();
var data = form.serialize();
});
Once you've done that, you can use $.post to submit the form data, handling it as you see fit:
form.on('submit', function(e){
e.preventDefault();
var url = form.attr('action');
var data = form.serialize();
$.post(url, data)
.done(function(response, status, jqxhr){
})
.fail(function(jqxhr, status, error){
});
});
Finally, put this all together in the shown.bs.modal event, so that it gets wired up once the dialog is visible:
debateModal.on('shown.bs.modal', function(){
var form = debateModal.find('form');
form.on('submit', function(e){
// prevent/cancel the native submit
e.preventDefault();
var url = form.attr('action'); // or use #Url.Action(), if you prefer
var data = form.serialize();
$.post(url, data)
.done(function(response, status, jqxhr){
/* Do what you need to with the response, and then close the modal */
debateModal.modal('hide');
})
.fail(function(jqxhr, status, error){
});
});
}
$.getJSON('#Url.Action("LoadFeedbackModal", "Home")').done(function(info) {
debateModal = bootbox.dialog(
{
message: info,
title: '<span class="fa fa-wechat"></span> Leave Feedback',
closeButton: true
});
debateModal.find('.modal-header').removeClass('modal-header').addClass('modal-header-info');
}).fail(function() {
debateModal = bootbox.alert({ message: "Problem try later", size: 'small' });
});
Suggest use getJSON instead of get, any question let me know.

Categories