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}));
});
});
});
Related
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()
I am trying to populate/fill a dropdown but I can't seem to get the values I need.
The "Employee Name" dropdown does not get populated while the "Platform Group" one does.
For "Employee Name" I use POST because this method is called by another VIEW in the software so I'd rather not change it.
I tried everything I could but the values will not show in the console or in the UI.
What am I missing?
Model
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace FXM.BO.ViewModels
{
public class NewAffiliateViewModel
{
public NewAffiliateViewModel()
{
}
public int Id { get; set; }
public string AffiliateName { get; set; }
public string Email { get; set; }
public int Employee { get; set; }
public int MT4Group { get; set; }
}
}
View
#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">
#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-10 ">
#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-10 ">
#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="//ajax.googleapis.com/ajax/libs/jquery/1.8.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");
var b = $("form").serialize();
//var a = $("form").serializeArray();
console.log("formvalues", b);
$.ajax({
url: "/en/AjaxUI/CreateAffiliate",
type: "GET",
dataType: "json",
data: 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
$(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());
});
$('#create-affiliate-button').select2({
theme: "bootstrap",
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; },
minimumInputLength: 0
});
</script>
Method in the Controller (for Employee Name)
[HttpPost]
[OutputCache(CacheProfile = "Cache10mn", Location = OutputCacheLocation.Client, NoStore = true)]
public JsonResult GetEmployeesExcept(int emplId, string t, bool searchByUserId=false)
{
t = string.IsNullOrWhiteSpace(t) ? String.Empty : t;
t = string.IsNullOrWhiteSpace(t) ? String.Empty : t;
if (!searchByUserId)
{
return Json(CrmServices.GetAllEmployees()
.Where(w => w.Id != emplId && string.Format("{1}{0}", w.UserDetails.Fullname, w.Id).ToLower().Contains(t.ToLower()))
.Select(s => new { id = s.Id, text = string.Format("{1} : {0}", s.UserDetails.Fullname, s.Id) }));
}
else
{
return Json(CrmServices.GetAllEmployees()
.Where(w => w.UserDetails != null && int.Parse(w.UserDetails.UserID) != emplId && string.Format("{1}{0}", w.UserDetails.Fullname, w.UserDetails.UserID).ToLower().Contains(t.ToLower()))
.Select(s => new { id = s.UserDetails.UserID, text = string.Format("{1} : {0}", s.UserDetails.Fullname, s.UserDetails.UserID) }));
}
}
method in the Controller (for "Platform Group")
public JsonResult CreateAffiliate(NewAffiliateViewModel newAffiliateViewModel)
{
try
{
var res = BackOfficeServices.BoAddAffiliateUser(newAffiliateViewModel);
//SystemServices.ResendEmail(userId);
return Json("success");
//return Json(null, JsonRequestBehavior.DenyGet);
}
catch (Exception e)
{
throw e;
}
}
Also, when I uncomment the code for the ajax request for "Employee Name", the "Platform group" stops being populated. When I comment it back, the "Platform group" is populated just fine.
Thank you for any response.
You need to search for : "Select2"
Here is site https://select2.org/
Read the guid, its easy
UPDATE 1:
Here is EXAMPLE of code, that you need, man.
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,
}
});
}
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.
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.