Form in ajax post method sends empty object - javascript

I have a webform with several fields I want to capture in an object and send it to a controller method. The form has this code:
<div class="panel-footer">
#using (Html.BeginForm("NuevaOpcion", "Home", FormMethod.Post, new { #id = "frm_nueva_opcion" })) {
#Html.HiddenFor(m => m.Id)
<div class="row">
<div class="col-md-6">
<div class="form-group" style="margin-bottom: .7em;margin-top: .7em;">
<button class="btn btn-success btn-xs" type="button" onclick=" $('#row-nueva-opcion').toggle()" id="add-opcion">
<span class="glyphicon glyphicon-plus-sign"></span> Añadir nueva opción
</button>
</div>
</div>
</div>
<div class="row" id="row-nueva-opcion" style="display:none">
<div class="col-md-10">
<label>
<input type="checkbox" id="opcion-extra" onclick=" $('#nuevo-precio').attr('disabled', !this.checked);" />
Es opción extra
</label>
<div class="input-group" style="margin-bottom:1.7em;">
<input type="text" placeholder="Opción" class="form-control" name="nombre" style="max-width:70%;">
<input type="number" placeholder="Cantidad" min="1" value="1" class="form-control" name="cantidad" style="max-width:15%;">
<input type="number" placeholder="Precio" class="form-control" id="nuevo-precio" name="precio" style="max-width:15%;" disabled>
<input type="hidden" name="idrespuesta" id="idrespuesta" value="#listItems.Select(x=>x.Value).FirstOrDefault()" />
<div class="input-group-addon">€</div>
<span class="input-group-btn">
<a class="btn btn-primary" data-title="Confirmación de acción" data-toggle="modal" data-target="#modal_confirm" onclick="confirmar('frm_nueva_opcion')">
<span class="glyphicon glyphicon-floppy-disk"></span> Guardar
</a>
</span>
</div>
</div>
<div class="col-md-8">
<div class="form-group">
<label>
¿Para que pregunta es la opción?
#Html.DropDownList("OptionSelectedItem", listItems, new { #class = "form-control" })
</label>
</div>
</div>
</div>
}
</div>
To manage it, I have a script that looks like this:
function mostrarModal(idmodal, mensaje, tipo) {
$(idmodal + ' .modal-body h4').addClass(tipo == 'error' ? 'text-danger' : 'text-secondary').html(mensaje);
$(idmodal).modal('show');
}
function enviar(form) {
debugger;
var NuevoPrecio = $('#' + form).attr("nuevo-precio");
if( (NuevoPrecio == null) || (typeof NuevoPrecio === "undefined") ) { var NuevoPrecio = 0; }
var datos = {
Id: $('#' + form).attr("#Id"),
IdPresupuestador: $('#' + form).attr("#idPresupuestador"),
IdRespuesta: $('#' + form).attr("#idrespuesta"),
Cantidad: $('#' + form).attr("#cantidad"),
Nombre: $('#' + form).attr("#nombre"),
Precio: NuevoPrecio,
}
$.post("NuevaOpcion", {
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(datos),
});
}
var modalConfirm = function (callback) {
$("#modal-btn-si").on("click", function () {
callback(true);
$("#modal-confirm").modal('hide');
});
$("#modal-btn-no").on("click", function () {
callback(false);
$("#modal-confirm").modal('hide');
}); };
function confirmar(form, text) {
$("#modal-confirm").modal('show');
modalConfirm(function (confirm) {
if (confirm) {
enviar(form);
}
}); };
Trouble is, I've changed the script on several points and now looks like this because the best I could manage was taking all the form in a single object. I can't work with the properties contained in that object, not on the script and neither on the controller method.
So, the question is, how am I selecting the fields wrong? I've tried with "#", ".", just the name between quotes, and as I said, the best I could get was the entire form in a single object. Thanks in advance.

Related

Using Modal JavaScript in the Partial View of .NET CORE will not work after Ajax Post

I use the Modal display field in the Partial View to input data for the User, and use data-url=#url.action("Create") in the main screen to call Modal.
And wrote Autocomplete JavaScript in Partial View.
It works perfectly before using Ajax Post.
But after going through Ajax, the JavaScript cannot be used when it returns because of an error.
How can I make corrections?
Main View
<div id="PlaceHolderHere" data-url="#Url.Action("Create")"></div>
Ajax Code
$(function () {
var PlaceHolderElement = $('#PlaceHolderHere');
$('button[data-toggle="ajax-modal"]').click(function (event) {
event.preventDefault();
var url = $(this).data('url');
$.get(url).done(function (data) {
PlaceHolderElement.html(data);
PlaceHolderElement.find('.modal').modal('show');
});
});
PlaceHolderElement.on('click', '[data-save="modal"]', function (event) {
event.preventDefault();
var form = $(this).parents('.modal').find('form');
var actionUrl = form.attr('action');
var sendData = new FormData(form.get(0));
console.log(sendData);
$.ajax({
url: actionUrl,
method: 'post',
data: sendData,
processData: false,
contentType: false,
cache: false,
success: function (redata) {
console.log(redata);
if (redata.status === "success") {
PlaceHolderElement.find('.modal').modal('hide');
}
else {
var newBody = $('.modal-body', redata);
var newFoot = $('.modal-footer', redata);
PlaceHolderElement.find('.modal-body').replaceWith(newBody);
PlaceHolderElement.find('.modal-footer').replaceWith(newFoot);
}
},
error: function (message) {
alert(message);
}
})
})
})
Partial View of JavaScript part
#{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
<script src="~/bootstrap-autocomplete/dist/latest/bootstrap-autocomplete.min.js"></script>
$('#BossName').autoComplete({
resolver: 'custom',
minLength: 2,
formatResult: function (item) {
return {
value: item.value,
text: "[" + item.value + "] " + item.text,
}
},
noResultsText:'There is no matching data, please confirm whether there is data in the company field',
events: {
search: function (qry, callback) {
// let's do a custom ajax call
$.ajax(
'#Url.Action("GetRolesByAutoComplete","Roles")',
{
data: {
'q': qry,
'key': document.getElementById('CompanyCode').value
}
}
).done(function (res) {
callback(res)
});
}
}
});
$('#BossName').on('autocomplete.select', function (evt, item) {
console.log(item);
$('#BossID').val(item.value);
$('#BossName').val(item.text);
});
Partial View of Modal
<div class="modal fade" id="AddEditRoles" tabindex="-1">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="AddEditRolesLabel">Add New Roles</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<form asp-action="Create" id="Edit">
<div class="input-group">
<span class="input-group-text">#Html.DisplayNameFor(m => m.RolesCode)</span>
#if (Model != null && Model.RolesCode != null)
{
<input asp-for="RolesCode" class="form-control" readonly />
}
else
{
<input asp-for="RolesCode" class="form-control" autocomplete="off" />
}
<span asp-validation-for="RolesCode" class="text-danger"></span>
</div>
<div class="input-group">
<span class="input-group-text">#Html.DisplayNameFor(m => m.Title)</span>
<input asp-for="Title" class="form-control" autocomplete="off" />
<span asp-validation-for="Title" class="text-danger"></span>
</div>
<div class="input-group">
<span class="input-group-text">#Html.DisplayNameFor(m => m.CompanyCode)</span>
<input type="text" asp-for="CompanyCode" class="form-control col-md-3" readonly />
<input type="text" id="CompanyName" class="form-control" autocomplete="off"
placeholder="Please type Key word" />
<span asp-validation-for="CompanyCode" class="text-danger"></span>
</div>
<div class="input-group">
<span class="input-group-text">#Html.DisplayNameFor(m => m.BossID)</span>
<input asp-for="BossID" type="text" class="form-control col-md-3" readonly />
<input id="BossName" type="text" class="form-control" autocomplete="off"
placeholder="Please type Key word" />
<span asp-validation-for="BossID" class="text-danger"></span>
</div>
</form>
</div>
<div class="modal-footer">
<div class="text-danger">#Html.ValidationMessage("error")</div>
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button id="Save" type="button" class="btn btn-primary" data-save="modal">Save changes</button>
</div>
</div>
</div>
</div>
You send data to the server, but when it fails you replace modal contents.
Replacing HTML destroys everything that was already there, so you wipe everything that was done by your autocomplete plugin.
All you need to do is to initialize autocomplete again:
success: function (redata) {
if (redata.status === "success") {
} else {
var newBody = $('.modal-body', redata);
var newFoot = $('.modal-footer', redata);
PlaceHolderElement.find('.modal-body').replaceWith(newBody);
PlaceHolderElement.find('.modal-footer').replaceWith(newFoot);
// INITIALIZE AUTOCOMPLETE HERE
}
},

How to submit form in jquery

This maybe a simple problem, but I can't find the cure.
When I executes this :-
$('#save_results').on("click", function () {
$('#formSaveQuotationPrepDetail').submit();
});
Everything works fine. But when I do this :-
$('#save_results').on("click", function () {
$('#formSaveQuotationPrepDetail').submit(function (e) {
var result = '#TempData["StatusMsg"]';
e.preventDefault();
if (result == 'Success') {
alert("Saved Successfully.");
}
})
});
This is my code behind :-
[HttpPost]
public ActionResult SaveQuotePreparation(QuotationPreparationEntity quoteP)
{
string result = objManager.SaveQuotePreparation(quoteP);
if (!string.IsNullOrEmpty(result) && (result == GeneralConstants.Inserted || result == GeneralConstants.Updated))
{
//Payment Gateway
data = GeneralConstants.SavedSuccess;
TempData["StatusMsg"] = "Success";
}
return new JsonResult { Data = data, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}
My HTML is a long code , I've made it short just for understanding :-
#using (Html.BeginForm("SaveQuotePreparation", "Technical", FormMethod.Post, new { #id = "formSaveQuotationPrepDetail" }))
{
<div class="row">
<form>
<div class="col-md-12 text-left">
<div class="row text-center">
<div class="col-md-4">
<div class="form-group text-left">
<label class="control-label ">
Quote Number
</label>
#Html.DropDownListFor(m => m.QuoteNo, new SelectList(#ViewBag.ListQuoteNo, "DataStringValueField", "DataTextField", Model.QuoteNo),
new
{
#class = "form-control requiredValidation",
#id = "QuoteNo",
#data_inneraction = "validationCall",
#onfocusout = "return ValidateRequiredFieldsOnFocusOut(this)"
})
<span class="HideValidMsg">Please Select QuoteNo</span>
</div>
</div>
<div class="col-md-4">
<div class="form-group text-left">
<label class="control-label">
Product Line
</label>
#Html.DropDownListFor(m => m.ProductLine, new SelectList(#ViewBag.ListProdGrp, "DataStringValueField", "DataTextField", Model.ProductLine),
new
{
#class = "form-control requiredValidation",
#id = "ProductLine",
#onfocusout = "return ValidateRequiredFieldsOnFocusOut(this)",
ng_model = "ProductLine",
ng_change = "GetProductLineDetails(ProductLine)"
})
<span class="HideValidMsg">Please Select ProductLine</span>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12 pt-4 text-center">
<button type="button" class="btn btn-success btn-sm" data-dismiss="modal" id="save_results">Save</button>
#*<input style="font-size:18px" type="button" class="btn btn-success btn-sm" data-dismiss="modal" id="save_results" value="Save" />*#
<input style="font-size:18px" type="button" class="btn btn-secondary btn-sm" data-dismiss="modal" value="Close" />
</div>
</div>
</form>
The Event don't fire on click. I don't get any error or anything.
I want to return JSON data on submit and show it as an alert on the screen.
You can do form submit in javascript like this..
$(document).on("submit", "form", function (event) {
event.preventDefault();
$.ajax({
url: $(this).attr("action"),
type: $(this).attr("method"),
dataType: "JSON",
data: new FormData(this),
processData: false,
contentType: false,
success: function (data, status) {
successFunction()
}
},
error: function (xhr, desc, err) {
}
});
});
The From will define like this
<form class="form-horizontal" id="frm" name="frm" action="/Controler/Action" method="post" enctype="multipart/form-data"></form>
And Need to create the button as submit
<input type="submit"/>
i dont have your html code but ,
if you want your form to be submitted by on click event :
$('#save_results').on("click", function () {
e.preventDefault();
$('#formSaveQuotationPrepDetail').submit();
if (result == 'Success') {
alert("Saved Successfully.");
}
});
take a look at this example to see difference between your first and second code .
NOTE : in your code result is not defined , i am not sure where have you brought it from
You did mistake in view page. Please remove <form> tag inside view page. It will work.
You only use below code instead of your code:
note: Html.Beginform() method work as tag in HTML
#using (Html.BeginForm("SaveQuotePreparation", "Technical", FormMethod.Post, new { #id = "formSaveQuotationPrepDetail" }))
{
<div class="row">
<div class="col-md-12 text-left">
<div class="row text-center">
<div class="col-md-4">
<div class="form-group text-left">
<label class="control-label ">
Quote Number
</label>
#Html.DropDownListFor(m => m.QuoteNo, new SelectList(#ViewBag.ListQuoteNo, "DataStringValueField", "DataTextField", Model.QuoteNo), new { #class = "form-control requiredValidation", #id = "QuoteNo", #data_inneraction = "validationCall", #onfocusout = "return ValidateRequiredFieldsOnFocusOut(this)" })
<span class="HideValidMsg">Please Select QuoteNo</span>
</div>
</div>
<div class="col-md-4">
<div class="form-group text-left">
<label class="control-label">
Product Line
</label>
#Html.DropDownListFor(m => m.ProductLine, new SelectList(#ViewBag.ListProdGrp, "DataStringValueField", "DataTextField", Model.ProductLine), new { #class = "form-control requiredValidation", #id = "ProductLine", #onfocusout = "return ValidateRequiredFieldsOnFocusOut(this)", ng_model = "ProductLine", ng_change = "GetProductLineDetails(ProductLine)" })
<span class="HideValidMsg">Please Select ProductLine</span>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12 pt-4 text-center">
<button type="button" class="btn btn-success btn-sm" data-dismiss="modal" id="save_results">Save</button>
#*<input style="font-size:18px" type="button" class="btn btn-success btn-sm" data-dismiss="modal" id="save_results" value="Save" />*#
<input style="font-size:18px" type="button" class="btn btn-secondary btn-sm" data-dismiss="modal" value="Close" />
</div>
</div>
</div>
}

Highlight error on specific textbox: KnockoutJS

Using asp.net mvc, c#, knockoutjs
I have a textarea and a ADD button next to it. User can enter in the textarea and press CHECK button or they can click the ADD button to add another textarea and then click CHECK button. There is no restriction to no of textarea they can add.
When they press the CHECK button I the code hits my MVC controller method and does some validations on the input. If the input is fine I proceed else show error.
My issue is highlighting and displaying the correct error. Right now I am just using one generic error label to show error. I want to show error to the textarea which has the error not a generic one. I have my code as below.
<form id="form" asp-controller="Home" asp-action="FilterMaintenance" method="post">
<div class="form-horizontal" style="margin-top:50px">
<div data-bind="foreach: { data: records }">
<div class="form-group">
<div class="col-md-6 ">
<textarea rows="1" class="required text-danger form-control textbox-wide" data-bind="value: $data.input, attr: { name: 'Records[' + $index() + '].Input', id: 'Records[' + $index() + '].Input'}"></textarea>
<span class="help-block-msg field-validation-valid" data-valmsg-replace="true" data-bind="attr: { 'data-valmsg-for': 'Records[' + $index() + '].Input'}"></span>
</div>
<div class="col-md-2">
<input type="button" value="Add Record" class="btn btn-primary" data-bind="click: $parent.addRecord, visible: function(){ return !($index() != $parent.records().length - 1) }()" />
</div>
</div>
</div>
<div class="form-group">
<div class="col-md-2">
<input type="button" value="Check Input" class="btn btn-primary" data-bind='click: checkInput' />
</div>
</div>
<div class="form-group" data-bind="visible: errorFlag">
<span data-bind="text: errorText"></span>
</div>
</div>
Knockout code:
(function () {
var viewModel = function (vmData) {
var self = this;
self.errorFlag = ko.observable(false);
self.errorText = ko.observable();
self.records = ko.observableArray();
self.records([{
input: ""
}]);
self.addRecord = function () {
self.records.push(
{
input: ""
});
};
self.checkInput = function () {
var returnVal = false;
var records = self.records();
var input = JSON.stringify(records);
//With abc as first and def as second texarea entry I get as below
//"[{"input":"abc"},{"input":"def"}]"
$.ajax({
type: "POST",
async: false,
url:"/Home/CheckRecord",
contentType: 'application/x-www-form-urlencoded; charset=utf-8',
data: {
"input": input
},
success: function (data) {
self.errorFlag(true);
if (data == '') {
self.errorText('Input is correct');
returnVal = true;
}
else {
self.errorText('Input is not correct: ' + data);
returnVal = false;
}
}
});
return returnVal;
}
}
var pageVM = new viewModel();
ko.applyBindings(pageVM, $("form")[0]);
})();
MVC Controller:
[HttpPost]
public IActionResult CheckRecord(string input)
{
string parseError = string.Empty;
bool inputCheck = false;
string returnValue = string.Empty;
inputCheck = false;//doing some checks here then return true or false
returnValue = inputCheck ? "" : "error";
var ret = Json(returnValue);
return ret;
}
Also I get the below generated HTML for 2 textarea added:
<div class="form-group">
<div class="col-md-6 ">
<textarea rows="1" class="required text-danger form-control textbox-wide" data-bind="value: $data.input, attr: { name: 'Records[' + $index() + '].Input', id: 'Records[' + $index() + '].Input'}" name="Records[0].Input" id="Records[0].Input"></textarea>
<span class="help-block-msg field-validation-valid" data-valmsg-replace="true" data-bind="attr: { 'data-valmsg-for': 'Records[' + $index() + '].Input'}" data-valmsg-for="Records[0].Input"></span>
</div>
<div class="col-md-2">
<input type="button" value="Add Record" class="btn btn-primary" data-bind="click: $parent.addRecord, visible: function(){ return !($index() != $parent.records().length - 1) }()" style="display: none;">
</div>
</div>
<div class="form-group">
<div class="col-md-6 ">
<textarea rows="1" class="required text-danger form-control textbox-wide" data-bind="value: $data.input, attr: { name: 'Records[' + $index() + '].Input', id: 'Records[' + $index() + '].Input'}" name="Records[1].Input" id="Records[1].Input"></textarea>
<span class="help-block-msg field-validation-valid" data-valmsg-replace="true" data-bind="attr: { 'data-valmsg-for': 'Records[' + $index() + '].Input'}" data-valmsg-for="Records[1].Input"></span>
</div>
<div class="col-md-2">
<input type="button" value="Add Record" class="btn btn-primary" data-bind="click: $parent.addRecord, visible: function(){ return !($index() != $parent.records().length - 1) }()">
</div>
</div>
Sorry for the long post but wanted to show the full code for explanation.
Any inputs are appreciated.
Update:
I have a added this in jsfiddle as well:
https://jsfiddle.net/gmmmh873/
I would recommend looking at Knockout-Validation. It can handle most of this for you, and has great documentation to get you started. This injects error messages per input field when the rules are not met. You can also trigger these from the response back from your xhr call as well.

Save multiple dynamically added file in mongoose

I'm using Ajax to add (and remove) multiple fields in a form, and then submitting them to mongoose to save them. Unfortunatelly I'm able to retrieve and save only 1 array, missing completely the dinamically added ones.
HTML: Here's a form with a form-group visible, where I inizialise the array using name attributes,and a form-group template that I dinamically populate with Ajax
<form id="productAdd" class="form-horizontal" method="post" enctype="multipart/form-data" action="?_csrf={{csrfToken}}">
<section class="panel">
<div class="panel-body">
<div class="form-group" data-option-index="1">
<label class="col-md-3 control-label" for="optionType">Type</label>
<div class="col-md-1">
<select class="form-control" name="options[0][optionType]">
<option value="grams">Gr.</option>
</select>
</div>
<label class="col-md-1 control-label" for="value">Value</label>
<div class="col-md-1">
<input type="text" class="form-control" name="options[0][optionValue]">
</div>
<label class="col-md-1 control-label" for="price">Price</label>
<div class="col-md-1">
<input type="text" class="form-control" name="options[0][optionPrice]">
</div>
<div class="col-md-1">
<button type="button" class="btn btn-default addButton"><i class="fa fa-plus"></i></button>
</div>
</div>
<div class="form-group hide" id="optionTemplate">
<label class="col-md-3 control-label" for="optionType">Type</label>
<div class="col-md-1">
<select class="form-control" name="optionType">
<option value="grams">Gr.</option>
</select>
</div>
<label class="col-md-1 control-label" for="value">Value</label>
<div class="col-md-1">
<input type="text" class="form-control" name="optionValue">
</div>
<label class="col-md-1 control-label" for="price">Price</label>
<div class="col-md-1">
<input type="text" class="form-control" name="optionPrice">
</div>
<div class="col-md-1">
<button type="button" class="btn btn-default removeButton"><i class="fa fa-minus"></i></button>
</div>
</div>
</div>
<footer class="panel-footer">
<div class="row">
<div class="col-sm-9 col-sm-offset-3">
<input type="hidden" name="_csrf" value="{{csrfToken}}">
<button class="btn btn-primary">Submit</button>
<button type="reset" class="btn btn-default">Reset</button>
</div>
</div>
</footer>
</section>
</form>
AJAX: I use this to add rows or remove them, each with 3 inputs. Before submitting the form I use .serialize() to get the arrays by their names
$(document).ready(function() {
var optionIndex = $(".form-group[data-option-index]").length;
$('#productAdd').submit(function(e) { // add product submit function
e.preventDefault();
$(this).ajaxSubmit({
contentType: 'application/json',
data: $('form[name="productAdd"]').serialize(),
error: function(xhr) {
console.log('Error: ' + xhr.status + ' ---- ' + xhr.responseText);
},
success: function(response) {
if (typeof response.redirect === 'string')
window.location = response.redirect;
}
});
return false;
})
// Add button click handler
.on('click', '.addButton', function() {
optionIndex++;
var $template = $('#optionTemplate'),
$clone = $template
.clone()
.removeClass('hide')
.removeAttr('id')
.attr('data-option-index', optionIndex)
.insertBefore($template);
// Update the name attributes
$clone
.find('[name="optionType"]').attr('name', 'options[' + optionIndex + '].optionType').end()
.find('[name="optionValue"]').attr('name', 'options[' + optionIndex + '].optionValue').end()
.find('[name="optionPrice"]').attr('name', 'options[' + optionIndex + '].optionPrice').end();
})
// Remove button click handler
.on('click', '.removeButton', function() {
var $row = $(this).parents('.form-group'),
index = $row.attr('data-option-index');
// Remove fields
$row.find('[name="options[' + index + '].title"]').remove();
$row.find('[name="options[' + index + '].isbn"]').remove();
$row.find('[name="options[' + index + '].price"]').remove();
// Remove element containing the fields
$row.remove();
});
});
NODEJS: Here's my nodejs route, I use multer for managing file upload. I've a foreach should manage the inputs from the form, but it just see the first element.
router.post('/shop/products/add', [isLoggedIn, multer({dest: './public/images/products/'}).single('productPhoto')], function(req, res, next) {
var newProduct = new Product();
newProduct.imagePath = req.file.filename;
newProduct.title = req.body.title;
newProduct.description = req.body.description;
newProduct.price = req.body.price;
newProduct.save()
.then(function (product) {
console.log(req.body.options);
req.body.options.forEach(function (option) {
var newOption = new ProductOption();
newOption.type = option.optionType;
newOption.value = option.optionValue;
newOption.price = option.optionPrice;
newOption.product = product;
newOption.save();
});
})
.then(function (options) {
req.flash('success', 'Product uploaded correctly.');
res.send({redirect: '/user/shop/products/add'});
})
.catch(function (err) {
console.log('Error ' + err.code + ': ', err.message);
res.status(500).send('Failed to save the newAddress to DB: ' + err);
});
});
It was a simple mistake, I named the fields dinamically added, differently from the static ones.
this code
.find('[name="optionType"]').attr('name', 'options[' + optionIndex + '].optionType').end()
should be like this
.find('[name="optionType"]').attr('name', 'options[' + optionIndex + '][optionType]').end()

How to update Parent form from a Modal

I have a modal form that updates a client's address once the "save" button is clicked. I want to use a AJAX call to update the Model's data once the modal form is closed. It would then redirect back to the parent form from which the modal form was called (Index.cshtml). The AJAX call is successfully retrieving the updated modal form's data via the textboxes but it always throws an error.
TL;DR: Want to close a modal form, redirect to parent form and update the text displayed there.
Please see below for my code snippets:
Controller
[ValidateInput(false), HttpPost]
public JsonResult UpdateClientDetails(Client newClientDetails)
{
_clientService.UpdateClient(newClientDetails);
return Json(newClientDetails);
}
$('.btn-update-client').click(function (e) {
var id = $(this).val();
$('#updateClientModal .modal-content').load('/client/UpdateClientDetails/' + id);
$('#updateClientModal').modal('show');
});
View (Index.cshtml)
<div class="panel-body">
<label>Client Id: <span id="ClientId">#id</span></label>
<address>
<span id="Address1">#client.Address1</span>, <span id="Address2">#client.Address2</span><br>
<span id="City">#client.City</span>, <span id="Province">#client.Province</span><br>
<span id="PostalCode">#client.PostalCode</span><br>
<abbr title="Phone">P:</abbr> <span id="PhoneNumber">#client.PhoneNumber</span>
</address>
<div><button value="#id" type="button" class="btn btn-primary btn-update-client">Change</button></div>
</div>
__
Controller Method
public ActionResult Index()
{
return View(_clientService.GetClientList());
}
Modal Form
#model Client
#using ProductManager.Models
<div class="modal-header">
<h4 class="modal-title" id="exampleModalLabel">#Model.Name - ID: #Model.Id</h4>
</div>
#{
var attributes = new Dictionary<string, object>();
attributes.Add("class", "form-horizontal");
}
#using (Html.BeginForm("UpdateClientDetails", "Client", FormMethod.Post, attributes))
{
<div class="modal-body">
<div class="form-group">
<label for="clientAddress1" class="col-xs-3 control-label">Address 1</label>
<div class="col-xs-9">
<input type="text" class="form-control" id="clientAddress1" name="Address1" value="#Model.Address1">
</div>
</div>
<div class="form-group">
<label for="clientAddress2" class="col-xs-3 control-label">Address 2</label>
<div class="col-xs-9">
<input type="text" class="form-control" id="clientAddress2" name="Address2" value="#Model.Address2">
</div>
</div>
<div class="form-group">
<label for="clientCity" class="col-xs-3 control-label">City</label>
<div class="col-xs-9">
<input type="text" class="form-control" id="clientCity" name="City" value="#Model.City">
</div>
</div>
<div class="form-group">
<label for="clientProvince" class="col-xs-3 control-label">Province</label>
<div class="col-xs-9">
#Html.DropDownListFor(model => model.Province, (IEnumerable<SelectListItem>)ViewBag.ProvinceList, new { #class = "form-control", #id = "clientProvince" })
</div>
</div>
<div class="form-group">
<label for="clientPostalCode" class="col-xs-3 control-label">Postal Code</label>
<div class="col-xs-9">
<input type="text" class="form-control" id="clientPostalCode" name="PostalCode" value="#Model.PostalCode">
</div>
</div>
<div class="form-group">
<label for="clientPhoneNumber" class="col-xs-3 control-label">Phone #</label>
<div class="col-xs-9">
<input type="text" class="form-control" id="clientPhoneNumber" name="PhoneNumber" value="#Model.PhoneNumber">
</div>
</div>
<div>
<input type="hidden" id="clientName" name="Name" value="#Model.Name">
</div>
<div>
<input type="hidden" id="clientID" name="Id" value="#Model.Id">
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-primary">Save changes</button>
</div>
}
<script type="text/javascript">
$('.btn-primary').click(function () {
$.ajax({
type: 'POST',
data: getModelData(),
dataType: 'json',
success: function (data) {
$("#Address1").text(data.Address1);
$("#Address2").text(data.Address2);
$("#City").text(data.City);
$("#Province").text(data.Province);
$("#PostalCode").text(data.PostalCode);
$("#PhoneNumber").text(data.PhoneNumber);
},
error: function () {
alert("Error occured!");
}
});
function getModelData() {
var dataToSubmit = {
Address1: $("#clientAddress1").val(),
Address2: $("#clientAddress2").val(),
City: $("#clientCity").val(),
Province: $("#clientProvince").val(),
PostalCode: $("#clientPostalCode").val(),
PhoneNumber: $("#clientPhoneNumber").val()
};
return dataToSubmit;
}
});
</script>
After clicking the "Save" button on my modal form, it redirects to http://localhost:6969/Client/UpdateClientDetails/1234 with the following string:
{"Address1":"38 Lesmill Rd","Address2":"Suite 1",
"City":"Toronto","Province":"ON","PostalCode":"M3B 2T5",
"PhoneNumber":"(416) 445-4504","Id":2827,"Name":"Advisor Centric"}
If you are being redirected when you click the save function, it could be due to a few reasons. The below snippet should solve your problems.
$(document).on('click', '.btn-primary', function (event) {
event.preventDefault();
$.ajax({
type: 'POST',
data: getModelData(),
dataType: 'json',
success: function (data) {
$("#Address1").text(data.Address1);
$("#Address2").text(data.Address2);
$("#City").text(data.City);
$("#Province").text(data.Province);
$("#PostalCode").text(data.PostalCode);
$("#PhoneNumber").text(data.PhoneNumber);
},
error: function () {
alert("Error occurred!");
}
});
function getModelData() {
var dataToSubmit = {
Address1: $("#clientAddress1").val(),
Address2: $("#clientAddress2").val(),
City: $("#clientCity").val(),
Province: $("#clientProvince").val(),
PostalCode: $("#clientPostalCode").val(),
PhoneNumber: $("#clientPhoneNumber").val()
};
return dataToSubmit;
}
});
Changes to snippet explained:
Instead of using the jQuery click method, I have updated this to use the on method. This will allow us to attach an event to the btn-primary class even if it is loaded after the dom has been rendered.
We are now passing in the event object into the method. This allows us to prevent any default behavior that is expected, for example submitting the form traditionally. This is accomplished with the event.preventDefault() method.

Categories

Resources