Customize the view of Select2 Dropdown - javascript

In my view, I'm using select2Combobox as my dropdowns.
Here when the Country selection changes, I pass that selected id to the JSON result and get the results, assigning for the provinces Combobox.
When it happens, the dropdown view is changed to the square from the rounded edges.
I want to know how to add the same styles to the select2 combo boxes.
this is my code.
<div class="col-md-6 col-sm-6">
<div class="form-group row"> #Html.LabelFor(model => model.Country_Id, htmlAttributes: new { #class = "control-label col-md-3 required" }) <div class="col-sm-8">
<span class="asterisk_input"></span> #Html.DropDownList("Country_Id", null, "Select Country", new { #class = "form-control js-dropdown js-Country", #Id = "Country", #data_map = Model.TempId, #required = true }) #Html.ValidationMessageFor(model => model.Country_Id, "", new { #class = "text-danger" })
</div>
</div>
</div>
<div class="col-md-6 col-sm-6">
<div class="form-group row"> #Html.LabelFor(model => model.Province_Id, htmlAttributes: new { #class = "control-label col-md-3 required" }) <div class="col-sm-8">
<span class="asterisk_input"></span> #Html.DropDownListFor(model => model.Province_Id, new List <SelectListItem>(), new { #class = "form-control js-dropdown js-Province", #id = "ddlProvId" + Model.TempId, #data_map = Model.TempId, #required = true }) #Html.ValidationMessageFor(model => model.Province_Id, "", new { #class = "text-danger" })
</div>
</div>
</div>
Javascript
$(function () {
$('.js-Country').change(function () {
var mapperId = $(this).data('map');
setDropDownProvinces($(this).val(), mapperId)
});
});
function setDropDownProvinces(xVal, mapid) {
try {
$("#ddlProvId" + mapid).empty().trigger("changed");
$.ajax({
url: '/Account/FindProvinces',
type: 'POST',
dataType: 'json',
cache: false,
async: false,
data: {
CountryId: xVal
},
success: function (data) {
if (data.Success == true) {
$("#ddlProvId" + mapid).select2({
width: '100%',
data: JSON.parse(data.items)
});
}
}
});
} catch (err) {
console.log(err.message)
}
}
This is the dropdown before selecting the country
This is after the selection.

In the success function of your ajax call try this line after mapping the result:
$("#ddlProvId" + mapid).addClass('form-control js-dropdown js-Province');
Source:
jQuery $.addClass()

Related

sending attachment from view to Controller using Ajax Begin Form

In my web application, I am using the AjaxBeginForm method to send data to the controller without submitting the form and refreshing the page.
Here is my current code when I click the confirm button it passes the data in PaymentType, PayAmount and Note but not passing the attachment as a byte.
Is there any way of doing this or an alternative way?
This is my current code.
In the View
< div class = "x_panel" >
#using (Ajax.BeginForm("UpdatePayments", "TaskMains", new AjaxOptions { HttpMethod = "POST", InsertionMode = InsertionMode.Replace, UpdateTargetId = "PartialViewPaymentHistory" },
new
{
id = "frmTPaymnets"
}))
{
<div class="row">
<div class="col-md-4 col-sm-4">
<div class="form-group row">
#Html.LabelFor(model = > model.TaskDetailsList.First().Service_Price, htmlAttributes: new { #class = "control-label col-md-3" })
< div class = "col-sm-8" >
#Html.EditorFor(model = > model.TaskDetailsList.First().Service_Price, new { htmlAttributes = new { #class = "form-control", #disabled = "disabled" } })
</div>
</div>
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="row">
#Html.HiddenFor(model = > model.TaskDetailsList.First().Id)
<div class="col-md-4 col-sm-4">
<div class="form-group row">
#Html.LabelFor(model = > model.TaskPaymentsViewModel.Payment_Type, htmlAttributes: new { #class = "control-label col-md-3" })
< div class = "col-sm-8" >
#Html.DropDownList("Payment_Type", null, "Select Payment Type", new { #class = "form-control js-dropdown js-PaymentType", #Id = "PayType" })
#Html.ValidationMessageFor(model = > model.TaskPaymentsViewModel.Payment_Type, "", new { #class = "text-danger" })
< /div>
</div>
</div>
<div class="col-md-2 col-sm-3">
<div class="form-group row">
#Html.LabelFor(model => model.TaskPaymentsViewModel.Cash_Direction, htmlAttributes: new { #class = "control-label col-md-6" })
<div class="col-sm-4">
#Html.EditorFor(model => model.TaskPaymentsViewModel.Cash_Direction, new { htmlAttributes = new { #class = "form-control", #id = "txtCashDirection", #disabled = "disabled" } })
#Html.ValidationMessageFor(model => model.TaskPaymentsViewModel.Cash_Direction, "", new { #class = "text-danger" })
</div>
</div>
</div>
<div class="col-md-2 col-sm-4">
<div class="form-group row">
#Html.LabelFor(model = > model.TaskPaymentsViewModel.Amount, htmlAttributes: new { #class = "control-label col-md-3" })
< div class = "col-sm-8" > #Html.EditorFor(model = > model.TaskPaymentsViewModel.Amount, new { htmlAttributes = new { #class = "form-control", placeholder = "Type Bill Amount", #id = "txtAmount" } })
#Html.ValidationMessageFor(model = > model.TaskPaymentsViewModel.Amount, "", new { #class = "text-danger" })
</div>
</div>
</div>
<div class="col-md-4 col-sm-4">
<div class="form-group row">
#Html.LabelFor(model => model.TaskPaymentsViewModel.Note, htmlAttributes: new { #class = "control-label col-md-3" })
<div class="col-sm-8">
#Html.EditorFor(model => model.TaskPaymentsViewModel.Note, new { htmlAttributes = new { #class = "form-control", placeholder = "Type Additional Notes here" } })
#Html.ValidationMessageFor(model => model.TaskPaymentsViewModel.Note, "", new { #class = "text-danger" })
</div>
</div>
</div>
<div class="col-md-3 col-sm-6">
<div class="form-group">
Attachment
<div class="col-md-10">
<input type="file" name="ImageData" id="ImageData" multiple="multiple" data-id="Img" onchange="checkImage(this)" />
#Html.ValidationMessageFor(model => model.Attachment, "", new { #class = "text-danger" })
</div>
</div>
<img id="Img" src="" alt="" width="100" height="100" class="ml-1" />
</div>
<input type="button" onClick="UpdatePayments();"/>
</div>
Script for attachment section
<script type="text/javascript">
$('.js-dropdown').select2({
width: '100%', // need to override the changed default
});
function checkImage(obj) {
var fileExtension = ['jpeg', 'jpg', 'png', 'gif', 'bmp', 'pdf'];
var ResponceImgId = $(obj).data('id');
const fileSize = obj.files[0].size / 1024 / 1024; // in MiB
const fileSizeRule = 3.0;
if ($.inArray($(obj).val().split('.').pop().toLowerCase(), fileExtension) == -1) {
Swal.fire({
icon: 'error',
title: 'Upload Error',
text: 'Only .jpeg, .jpg, .png, .gif, .bmp ,pdf formats are allowed.',
footer: 'Please attach again'
})
}
else if (fileSize > fileSizeRule) {
Swal.fire({
icon: 'error',
title: 'Maximum size exceeded',
text: 'File size should be less than 3 MB.',
footer: 'Please add a attachment less than 3 MB'
})
}
else {
var files = obj.files;
var reader = new FileReader();
name = obj.value;
reader.onload = function (e) {
$('#' + ResponceImgId).prop('src', e.target.result);
};
reader.readAsDataURL(files[0]);
}
}
</script>
This is the ajax call
function UpdatePayments() {
try {
var $form = $("#frmTPaymnets");
var xModel = $form.serialize();
$.ajax({
url: '../UpdatePayments',
type: 'POST',
dataType: 'html',
cache: false,
async: false,
data: xModel,
success: function (data) {
$("#PartialViewPaymentHistory").html(data);
toastr.success('#ViewBag.ToastSucess');
document.getElementById('txtAmount').value = "";
}
});
}
catch (err) {
console.log(err.message)
}
}

select2 - dropdown options don't get selected on click

I have this Razor dropdown that gets the info from the DB via ajax but the options that show on the dropdown don't get selected. How to make the dropdown options become selected on click?
I tried to implement the answer to a similar question but it didn't work:
select2 load data using ajax cannot select any option
This is what I have so far:
Ajax
$(document).ready(function () {
$.validator.addMethod("regxPhone", function (value, element, regexpr) {
return regexpr.test(value);
}),
$.validator.addMethod("regxEmail", function (value) {
return /^([\w!.%+\-])+##([\w\-])+(?:\.[\w\-]+)+$/.test(value);
}),
$.validator.addMethod('validEmail', function (value, element, param) {
return valiEmailAjax($("#Email").val());
});
$('#dropdown-employees').select2({
minimumInputLength: 0,
multiple: false,
dropdownParent: $('#dropdown-email-for-select2'),
ajax: {
url: "/en/BOEmployeeAjax/GetEmployeesExcept",
type: "POST",
dataType: "json",
data: function (params) {
return {
emplId: 0,
t: params.term
}
},
processResults: function (data, params) {
return { results: data }
}
},
placeholder: window.selectAnotherSupervisor,
escapeMarkup: function (markup) { return markup; },
});
Razor dropdown
<div class="col-md-4 fieldSize4" id="dropdown-employees">
#Html.DropDownListFor(x => x.Employee, new SelectList(new Dictionary<string, string>(), "Key", "Value"), #FXM.BO.Strings.T("ddl_select_option"), new { #class = "form-control select2-allow-clear", #placeholder = "Select Symbols" })
<span class="help-block">
#FXM.BO.Strings.T("lbl_employee_description")
</span>
</div>
Code after 1st changes:
#model FXM.BO.ViewModels.NewAffiliateViewModel
#{
ViewBag.Title = "CreateAffiliate";
Layout = "~/Views/Shared/_LoggedInLayout.cshtml";
}
<h2>Create Affiliate</h2>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4 class="hidden">NewAffiliateViewModel</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.AffiliateName, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.AffiliateName, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.AffiliateName, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group" id="dropdown-email-for-select2">
#Html.LabelFor(model => model.Email, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#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(model => model.Employee, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Employee, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Employee, "", new { #class = "text-danger" })
</div>
</div>*#
#*<div class="form-group">
#Html.LabelFor(model => model.MT4Group, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.MT4Group, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.MT4Group, "", new { #class = "text-danger" })
</div>
</div>*#
<div class="form-group">
<label class="control-label col-md-2">
#FXM.BO.Strings.T("employeeName") <span class="required">
#***#
</span>
</label>
#*<div class="col-md-4 fieldPositionCol4 select2-bootstrap-prepend">*#
<div class="col-md-4 fieldSize4" id="dropdown-employees">
#Html.DropDownListFor(x => x.Employee, new SelectList(new Dictionary<string, string>(), "Key", "Value"), #FXM.BO.Strings.T("ddl_select_option"), new { #class = "form-control select2-allow-clear", #placeholder = "Select Symbols" })
<span class="help-block">
#FXM.BO.Strings.T("lbl_employee_description")
</span>
</div>
#*<img id="tpLoader" src="~/Content/images/ajax-loader.gif" class="hidden" />*#
</div>
<div class="form-group">
<label class="control-label col-md-2">
#FXM.BO.Strings.T("lbl_Bo_TradAcc_PlatformGroup") <span class="required">
#***#
</span>
</label>
#*<div class="col-md-4 fieldPositionCol4 select2-bootstrap-prepend">*#
<div class="col-md-4 fieldSize4">
#Html.DropDownListFor(x => x.MT4Group, new SelectList(new Dictionary<string, string>(), "Key", "Value"), #FXM.BO.Strings.T("ddl_select_option2"), new { #class = "form-control select2-allow-clear", #placeholder = "Select Symbols" })
<span class="help-block">
#FXM.BO.Strings.T("platform_group_description")
</span>
</div>
<img id="tpLoader" src="~/Content/images/ajax-loader.gif" class="hidden" />
</div>
#*Create button*#
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="button" value="Create" class="btn btn-default" id="create-affiliate-button" />
</div>
</div>
</div>
}
#*<div>
#Html.ActionLink("Back to List", "Index")
</div>*#
<script type="text/javascript" src="/Scripts/CustomScripts/Common/form-helpers.js"></script>
<script src="https://cdn.jsdelivr.net/npm/select2#4.1.0-rc.0/dist/js/select2.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/select2#4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript">
// document.ready function
$(function () {
refreshGroups();
// selector has to be . for a class name and # for an ID
$('#create-affiliate-button').click(function (e) {
//e.preventDefault(); // prevent form from reloading page
console.log("blahblahblah");
//alert("hiii");
var b = $("form").serialize();
//var a = $("form").serializeArray();
console.log("formvalues", b);
$.ajax({
url: "#Url.Action("CreateAffiliate", "AjaxUI")",
type: "GET",
dataType: "json",
data: {
newAffiliateViewModel : b
},
//error: function (jqXHR, exception) {
// failMessage();
//}
});
});
});
function refreshGroups() {
var pltf = "MT4_LIVE";
var out = $('#MT4Group');
if (pltf != null && pltf !== "") {
$.ajax({
url: '/' + window.currentLangCulture + '/BOLiveForms/GetPlatformGroupByFilter',
data: {
platform: pltf, currency: "", withId : true
},
type: 'GET',
beforeSend: function () {
$('#tpLoader').show();
},
complete: function () {
$('#tpLoader').hide();
},
success: function (data) {
populateDropDown(out, data);
//$('#recomandedGroup').show();
}
});
} else {
out.empty();
out.append($('<option></option>').val('').html(window.defaultSelection));
}
}
//GetEmployeesExcept - Method that populates the Dropdown for EmployeeName
$(document).ready(function () {
$.validator.addMethod("regxPhone", function (value, element, regexpr) {
return regexpr.test(value);
}),
$.validator.addMethod("regxEmail", function (value) {
return /^([\w!.%+\-])+##([\w\-])+(?:\.[\w\-]+)+$/.test(value);
}),
$.validator.addMethod('validEmail', function (value, element, param) {
return valiEmailAjax($("#Email").val());
});
var WithId = $('#dropdown-employees');
if(WithId.length>0){
var ajax_url = '/en/BOEmployeeAjax/GetEmployeesExcept';
var $ajax = WithId;
loadSelectData();
}
});
function loadSelectData() {
var cstoken = $('input[name="_token"]').val();
$ajax.select2({
ajax: {
url: ajax_url,
dataType: 'json',
data: function (params, cstoken, page) {
return {
"_token": cstoken,
searchtxt: params.term, // search term
page: params.page
};
},
processResults: function (data) {
var vh = [];
var obj = jQuery.parseJSON(data);
$.each(obj, function(key,value) {
var itemName = value.empname;
var itemId = value.id;
vh.push({id: itemId, text: itemName });
});
console.log(vh);
return {
results: vh,
pagination: {
more: true
}
}
},
placeholder: 'Search for a result',
minimumInputLength: 1,
}
});
}
</script>
Please change your select2 ajax code like.
Please change your select2 ajax code like.
$(document).ready(function () {
$.validator.addMethod("regxPhone", function (value, element, regexpr) {
return regexpr.test(value);
}),
$.validator.addMethod("regxEmail", function (value) {
return /^([\w!.%+\-])+##([\w\-])+(?:\.[\w\-]+)+$/.test(value);
}),
$.validator.addMethod('validEmail', function (value, element, param) {
return valiEmailAjax($("#Email").val());
});
var WithId = $('#dropdown-employees');
if(WithId.length>0){
var ajax_url = '/en/BOEmployeeAjax/GetEmployeesExcept';
var $ajax = WithId;
loadSelectData();
}
});
function loadSelectData() {
var cstoken = $('input[name="_token"]').val();
$ajax.select2({
ajax: {
url: ajax_url,
dataType: 'json',
data: function (params, cstoken, page) {
return {
"_token": cstoken,
searchtxt: params.term, // search term
page: params.page
};
},
processResults: function (data) {
var vh = [];
var obj = jQuery.parseJSON(data);
$.each(obj, function(key,value) {
var itemName = value.empname;
var itemId = value.id;
vh.push({id: itemId, text: itemName });
});
console.log(vh);
return {
results: vh,
pagination: {
more: true
}
}
},
placeholder: 'Search for a result',
minimumInputLength: 1,
}
});
}

relation between two dropdownlist in mvc

I have two dropdownlist,when i select an option from first one,related options show in second dropdown.i have used jquery but i dont know why it doesent work.
this is cshtml page:
<div class="form-group">
#Html.LabelFor(model => model.ProductSubGroup.ProductGroupID, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("ProductGroupID", (SelectList)ViewBag.Type, "-- انتخاب ---", htmlAttributes: new { #class = "form-control",id = "rdbGroup" })
#Html.ValidationMessageFor(model => model.ProductSubGroup.ProductGroupID, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.ProductSubGroupID, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("ProductSubGroupID", (SelectList)ViewBag.ProductSubGroupID, "-- انتخاب ---", htmlAttributes: new { #class = "form-control",id = "rdbSubGroup" })
#Html.ValidationMessageFor(model => model.ProductSubGroupID, "", new { #class = "text-danger" })
</div>
</div>
and this is controller
public ActionResult SelectCategory(int id)
{
var categoris = db.ProductSubGroup.Where(m => m.ProductGroup.ProductGroupID == id).Select(c => new { c.ProductSubGroupID, c.ProductSubGroupTitle});
return Json(categoris, JsonRequestBehavior.AllowGet);
}
// GET: Admin/Products/Create
public ActionResult Create()
{
ViewBag.ProductGroupID=new SelectList(db.ProductGroup,"ProductGroupID","Produ ctGroupTitle");
ViewBag.ProductSubGroupID = new SelectList(db.ProductSubGroup, "ProductSubGroupID", "ProductSubGroupTitle");
return View();
}
and this is javascript
$('#rdbGroup').change(function () {
jQuery.getJSON('#Url.Action("SelectCategory")', { id: $(this).attr('value') }, function (data) {
$('#rdbSubGroup').empty();
jQuery.each(data, function (i) {
var option = $('<option></option>').attr("value", data[i].Id).text(data[i].Title);
$("#rdbSubGroup").append(option);
});
});
});
a sample of mine
cs.html
<div class="form-group">
#Html.LabelFor(m => m.FakulteId, "Fakülte", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-6">
#Html.DropDownListFor(m => m.FakulteId, ViewBag.Fakulte as SelectList, "Fakülte Seçiniz", htmlAttributes: new { #class = "form-control", #id = "fakulteSec", #onchange = "secim()" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(m => m.BolumId, "Bölüm", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-6">
#Html.DropDownListFor(m => m.BolumId, ViewBag.Bolum as SelectList, "Bölüm Seçiniz", htmlAttributes: new { #class = "form-control", #id = "bolum" })
</div>
</div>
controller
public JsonResult FakulteBolumDrop(int id)
{
db.Configuration.ProxyCreationEnabled = false;
List<Bolum> bolum = db.Bolum.Where(b => b.FakulteId == id).ToList();
return Json(bolum, JsonRequestBehavior.AllowGet);
}
.js
function secim() {
var fakulteId = $('#fakulteSec').val();
//alert(fakulteId);
$.ajax({
url: '/Rektor/FakulteBolumDrop?id=' + fakulteId,
type: "POST",
dataType: "JSON",
data: { Fakulte: fakulteId },
success: function (bolumler) {
$("#bolum").html("");
$.each(bolumler, function (i, bolum) {
$("#bolum").append(
$('<option></option>').val(bolum.BolumId).html(bolum.Adi));
});
}
});
}
You have to register your change event of rdbGroup Drop Down inside the
$(document).ready(function(){
});
Otherwise it will not be fired.
use this.value or $(this).val() instead of $(this).attr('value').
Try
$('#rdbGroup').on('change',function () {// or $(document).on('change', '#rdbGroup',function (){
$.getJSON('#Url.Action("SelectCategory")', { id: this.value }, function (data) {
$('#rdbSubGroup').empty();
$.each(data, function (i,item) {// if data is json string form the replace data by $.parseJSON(data)
//console.log(item.Id); console.log(item.Title);
$('#rdbSubGroup').append($('<option>', {
value:item.Id,
text :item.Title
})); //OR you can use --- $('#rdbSubGroup').append($("<option></option>").attr("value",item.Id).text(item.Title));
});
});
});
OR
$('#rdbGroup').on('change',function () {// or $(document).on('change', '#rdbGroup',function (){
var id= this.value;
$.ajax({
url: '#Url.Action("SelectCategory")',
data: {
id: id
},
dataType: 'json',
async: false
}).done(function (data) {
$("#rdbSubGroup").html("");
$.each(data, function (i,item) {
$('#rdbSubGroup').append($("<option></option>").attr("value",item.Id).text(item.Title));
//OR $('#rdbSubGroup').append($('<option>', { value:item.Id, text :item.Title}));
});
});
});

Put jsonArray and other variables into one section in ajax passed to MVC controller

I have the following script
$(function () {
$("#btnConfirmParticipants").click(function () {
var jsonArray = [];
$(".participantForm").each(function () {
jsonArray.push({ Name: ($(this).find("#Name").val()), Surname: ($(this).find("#Surname").val()), BirthDate: ($(this).find("#BirthDate").val()) });
});
var data = {
participants: JSON.stringify(jsonArray),
houseName: $('select[name="SelectedHousesParticipants"]').val(),
__RequestVerificationToken: $('input[name=__RequestVerificationToken]').val()
};
$.ajax({
type: "POST",
url: "/ClientReservations/ChangeHouseParticipants",
data: data,
contentType: "application/json; charset=utf-8",
success: function (response) {
},
});
});
});
This script calls the method in controller
[HttpPost]
[Authorize(Roles ="Klient")]
public ActionResult ChangeHouseParticipants(List<Participant> participants,string houseName)
{
return View();
}
When during execution I receive
Invalid JSON primitives.
Any proposals how to solve it?
Additionaly using partial views to display each essential fields for every Participant
Partial View for all Participants
<div>
#foreach (Participant item in Model)
{
<div >
#Html.Partial("~/Views/Shared/_HouseParticipant.cshtml", item)
</div>
}
</div>
Partial view of single Participant
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal participantForm">
<h4>Uczestnik</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" } )
<div class="form-group">
#Html.LabelFor(model => model.Name, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Name, new { id = "Name", htmlAttributes = new { #class = "form-control" } })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Surname, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Surname, new { id = "Surname", htmlAttributes = new { #class = "form-control" } })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.BirthDate, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.BirthDate, new { id = "BirthDate", htmlAttributes = new { #class = "form-control" } })
</div>
</div>
</div>
}
Instead of
var data = {
participants: JSON.stringify(jsonArray),
houseName: $('select[name="SelectedHousesParticipants"]').val(),
__RequestVerificationToken: $('input[name=__RequestVerificationToken]').val()
};
do
var data = {
participants: jsonArray,
houseName: $('select[name="SelectedHousesParticipants"]').val(),
__RequestVerificationToken: $('input[name=__RequestVerificationToken]').val()
};
var jsonData = JSON.stringify(data);
and then pass jsonData in request.

Validation in jquery for bootstrap popup

Here is my View:
#using (Html.BeginForm("SaveNewCustomer", "Dealer", FormMethod.Post, new { id = "myForm" }))
{
<div class="form-horizontal">
<div class="row">
<div class="form-group-1">
#Html.LabelFor(model => model.device.MotorType, htmlAttributes: new { #class = "control-label col-lg-4" })
#Html.EditorFor(model => model.device.MotorType, new { htmlAttributes = new { #class = "form-control required", placeholder = "Motor Type", required = "required" } })
</div>
<div class="form-group-1">
#Html.LabelFor(model => model.device.PowerRating, htmlAttributes: new { #class = "control-label col-lg-4" })
#Html.EditorFor(model => model.device.PowerRating, new { htmlAttributes = new { #class = "form-control required", placeholder = "Power Rating", required = "required" } })
</div>
<div class="form-group-1">
#Html.LabelFor(model => model.device.InstallationDate, htmlAttributes: new { #class = "control-label col-lg-4" })
#Html.EditorFor(model => model.device.InstallationDate, new { htmlAttributes = new { #class = "form-control datepicker required", placeholder = "Installation Date(MM/dd/yyyy)", required = "required" } })
</div>
<div class="form-group-1">
#Html.LabelFor(model => model.device.ActivationDate, htmlAttributes: new { #class = "control-label col-lg-4" })
#Html.EditorFor(model => model.device.ActivationDate, new { htmlAttributes = new { #class = "form-control datepicker required", placeholder = "Activation Date(MM/dd/yyyy)", required = "required" } })
</div>
<div class="form-group-1">
#Html.LabelFor(model => model.device.DataReceiveInterval, htmlAttributes: new { #class = "control-label col-lg-4" })
#Html.EditorFor(model => model.device.DataReceiveInterval, new { htmlAttributes = new { #class = "form-control required", placeholder = "Data receive Interval", required = "required" } })
</div>
<div class="form-group-1">
#Html.LabelFor(model => model.device.HasAMC, htmlAttributes: new { #class = "control-label col-lg-4" })
#Html.EditorFor(model => model.device.HasAMC, new { htmlAttributes = new { #class = "form-control required", #onchange = "OnChange();" } })
</div>
<div class="form-group-1" id="HasDate">
#Html.LabelFor(model => model.device.AMCExpiredDate, htmlAttributes: new { #class = "control-label col-lg-4" })
#Html.EditorFor(model => model.device.AMCExpiredDate, new { htmlAttributes = new { #class = "form-control required", placeholder = "AMCExpireDate(MM/dd/yyyy)", required = "required", title = "Enter AMC Expire Date" } })
</div>
<button style="margin-left:33%;" id="action" class="btn btn-sm btn-primary col-lg-2 " type="button" name="action" value="SaveDeviceInfo"><strong>Save</strong></button>
</div>
</div>
}
My javascript script is
<script type="text/javascript">
$(document).ready(function () {
jQuery.validator.setDefaults({
debug: true,
success: "valid"
});
$( "#myForm" ).validate({
rules: {
"client.ContactNo": {
required: true
}
}
});
$("#action").click(function () {
if (!$("#myForm").validate()) { // Not Valid
return false;
} else {
Save();
}
});
function Save() {
var frm = $("#myForm").serialize();
$.ajax({
url: "/Dealer/SaveNewCustomer",
data: frm,
type: "POST",
success: function (result) {
if (result == "true") {
//alert(result);
window.location.href = "/Dealer/Customers?Success=true&Message=Customer updated successfully.";
}
else
toastr.error(result);
}
});
}
</script>
Problem is Validation not fire. In If else condition it is showing false and direct store the value in database. Could you please help me?
Is anything wrong in my code? Give me suggestions please.
Thanks in advance.
.validate() is only the initialization method.
.valid() is the method used for testing the form.
if (!$("#myForm").valid()) { ....
It's a moot point because your .ajax() function belongs inside the submitHandler option of the plugin anyway. The submitHandler callback only fires when the form is valid, thereby you can entirely eliminate your whole if/then click handler function (however you must change the button element into a type="submit").
$(document).ready(function () {
jQuery.validator.setDefaults({
debug: true,
success: "valid"
});
$( "#myForm" ).validate({
rules: {
"client.ContactNo": {
required: true
}
},
submitHandler: function(form) { // only fires when form is valid
var frm = $(form).serialize();
$.ajax({
url: "/Dealer/SaveNewCustomer",
data: frm,
type: "POST",
success: function (result) {
if (result == "true") {
//alert(result);
window.location.href = "/Dealer/Customers?Success=true&Message=Customer updated successfully.";
}
else
toastr.error(result);
}
});
return false;
}
});
});
NOTE: If you happen to be using the unobtrusive-validation plugin as included within your ASP framework, then the .validate() method is constructed and called automatically. If that's the case, then your call to .validate() will be ignored, and you would put any plugin options only within jQuery.validator.setDefaults().
You are missing your form tags from your html. Also, you dont have anything with the id of myform. So your trying to validate #myform in your jquery but there is no myform. You would need to add your form tags and give it an id of myform.

Categories

Resources