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,
}
});
}
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 written a html code for cshtml which consists two button save and update:
<div class="modal-body">
#using (Html.BeginForm("Create", "CustomActivity", FormMethod.Post, new { role = "form", #id = "customActivityForm", #class = "activityForm" }))
{
<div>
<div class="container" id="activity">
#Html.LabelFor(m => m.AdminCustomActivity.Activity, new { #class = "" })
#Html.TextBoxFor(m => m.AdminCustomActivity.Activity, new { #class = "w100p mb0" })
#Html.ValidationMessageFor(m => m.AdminCustomActivity.Activity, "", new { #class = "text-danger" })
</div>
<div class="container">
<div class="column one-fourth">
<div>
#Html.LabelFor(m => m.AdminCustomActivity.Rate, new { #class = "wcrate" })
#Html.TextBoxFor(m => m.AdminCustomActivity.Rate, new { #class = "w100p mb0" })
#Html.ValidationMessageFor(m => m.AdminCustomActivity.Rate, "", new { #class = "text-danger" })
</div>
</div>
</div>
<div class="modal-footer">
#Html.HiddenFor(m => m.AdminCustomActivity.WorkOrderId, new { #id = "hfWorkOrderId" })
#Html.HiddenFor(m => m.AdminCustomActivity.Id, new { #id = "customActivityId" })
<button type="submit" class="btn btn-primary">Create</button>
<button class="btn btn-primary" id="updateActivity">Update</button>
</div>
</div>
}
</div>
Now in the footer there is two button add and update the validation works perfect for add button but the validation dosen't works for Update button since the function call of update button is from jquery
$("#updateActivity").click(function () {
event.preventDefault();
$.ajax({
type: "POST",
url: "/CustomActivity/Update",
data: {
WorkOrderId: #Model.Id,
},
success: function () {
location.reload();
window.scrollTo(0, 0);
},
error: function () {
//alert(erro.data)
}
});
})
How can I allow to check validation in update button same as add bututon. I tried using type='submit' but that doesn't works
You would have to call a function which implements the jQuery validatation to show validation messages at the Update button click:
function validateUpdate() {
$("#customActivityForm").validate({
rules: {
AdminCustomActivity_Activity: "required",
AdminCustomActivity_Rate: "required"
}
});
}
$("#updateActivity").click(function () {
validateUpdate();
$.ajax({
type: "POST",
url: "/CustomActivity/Update",
data: {
WorkOrderId: #Model.Id,
},
success: function () {
location.reload();
window.scrollTo(0, 0);
},
error: function () {
//alert(erro.data)
}
});
})
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}));
});
});
});
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.