The below code generates 5 drop-down-lists.
#{
for (int i = 0; i < 5; i++) { <tr>
<td> #Html.Editor("[" + i + "].QNo", new { htmlAttributes = new { #class = "form-control ", #type = "text",
#placeholder = " QNo", #required = "", #id = "txtQNo", #style = "width:60px;" } }) </td>
<td> </td>
<td> #Html.DropDownList("[" + i + "].Question", new SelectList(string.Empty, "Value", "Text"), "Select Question",
new { #class = "form-control ", #id = "Question", #style = "width:900px;" })</td>
</tr>
}
}
I am trying to populate the above 5 drop-down menu with a bunch of values I receive through my below ajax call
$("#ReflectionType").on("change", function (event) {
$.ajax({
type: "post",
url: "/Question/GetQuestions",
data: { TypeId: $('#ReflectionType').val() },
datatype: "json",
traditional: true,
success: function (data) {
debugger;
$.each(data, function (index, value) {
var markup = '';
$("#Question").append('<option value="' + value.Question + '">' + value.Question + '</option>');
});
}
});
The above snippet only updates one of the drop-down list(the first drop-down menu) where it should be updating all five drop-down list.
#{
for (int i = 0; i < 5; i++) { <tr>
<td> #Html.Editor("[" + i + "].QNo", new { htmlAttributes = new { #class = "form-control ", #type = "text",
#placeholder = " QNo", #required = "", #id = "txtQNo", #style = "width:60px;" } })</td>
<td> </td>
<td> #Html.DropDownList("[" + i + "].Question", new SelectList(string.Empty,"Value", "Text"), "Select Question",
new { #class = "form-control ", #id = "Question"+i, #style = "width:900px;" })</td>
</tr>
}
}
This will generate unique id as follows Question0, Question1, Question2, Question3, Question4
$("#ReflectionType").on("change", function (event) {
$.ajax({
type: "post",
url: "/Question/GetQuestions",
data: { TypeId: $('#ReflectionType').val() },
datatype: "json",
traditional: true,
success: function (data) {
debugger;
$.each(data, function (index, value) {
var markup = '';
for(let j = 0; j < 5; j++){
$("#Question"+j).append('<option value="' + value.Question + '">' + value.Question + '</option>');
}
});
}
});
As I can see your loop is running through 5 iteration you can run it in the same way and append the data from ajax call. Or you can use starts with selector as follows
$('[id^=Question]').each(function(index,element){
$(element).append('<option value="' + value.Question + '">' + value.Question + '</option>');
})
Hopefully this will solve your problem. Happy Coding!
Related
Good day, i want to make when i select a value from any ddl , then a value next respective of each value input be displayed.image here. (https://i.stack.imgur.com/08DGz.png)
this is my html
<div class="row">
<div class="col-lg-6">
#Html.LabelFor(c => c.adaptadorJ)
#{ for (int i = 1; i <= 16; i++)
{
#Html.DropDownList("adaptadorJ" + i, itemAdaptadoresJs, "-J" + i + "-", new { #class = "form-control", #id = "J" + i, #onchange = "cambio(this)" })
}
}
</div>
<div class="col-lg-6">
#Html.LabelFor(c => c.asignaturaJ)
#{ for (int i = 1; i <= 16; i++)
{
#Html.TextBoxFor(c => c.asignaturaJ, new { #class = "form-control", #id = "asignaturaJInput" + i, autocomplete = "off", disabled = "disabled" })
}
}
</div>
</div>
this is my jquery ajax
function cambio(adaptador) {
var adaptadorID = adaptador.value;
$.ajax({
dataType: "json",
type: "POST",
url: '/Home/CambioAdaptador',
async: false,
data: {Adaptador: + adaptadorID },
success: function (result) {
$("#asignaturaJInput").val(result);
}
});
}
i used jquery, i just need to make that works.
I have a function and get the response from the controller.after that I need to append the details to the table.All I have done.But i can see the result only after I click the table .I think my datatable is not reloaded.How Can I solve this problem.My code is below.and html code is added here.When the select box changes according to the result the table is updated
$(document).on('change', '.MemberSelect', function () {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: JSON.stringify({ memberTypeID: $(".MemberSelect").val() }),
url: "#Url.Action("GetUserMenuDetails", "MenuPermission")",
success: function (data) {
var trHtml = '';
$('#tblClassName tbody').empty();
$.each(data, function (i, item) {
trHtml = trHtml + '<tr><td></td><td>' + (item.LibrarySchooberryMenuDetails!=null? item.LibrarySchooberryMenuDetails.MenuName : "") + '</td>'
'<td>' + item.MenuName + '</td>'
'<td><input type="checkbox" class="MenuMap" id="' + item.MenuID + '" data-id="' + item.MenuID + '"/></td>'
'<td><table>';
$.each(data.LibrarySchooberryMenuFunctions, function (j, functions) {
trHtml = trHtml + '<tr><td><input type="checkbox" class="FunctionMap" id="' + functions.MenuFunctionID + '" data-id="' + functions.MenuFunctionID + '"/>'
+ functions.Name + '<input type="hidden" value="' + functions.MenuID + '" class="menuID" /></td></tr>'
});
trHtml = trHtml + '</table></td></tr>'
});
$('#tblClassName').append(trHtml);
$('#tblClassName').DataTable({
'paging': true,
'lengthChange': false,
'searching': true,
'ordering': true,
'info': true,
'autoWidth': false
});
},
error: function (data) {
}
});
return false;
});
<div class="box-body">
<form id="MenuPermission">
<div class="form-group">
<select class="form-control MemberSelect" name="MemberType"></select>
</div>
<div id="example1_wrapper" class="dataTables_wrapper form-inline dt-bootstrap">
<table class="table table-bordered table-striped" id="tblClassName">
<thead>
<tr>
<th>Sl.NO
</th>
<th>Parent Menu
</th>
<th>Menu
</th>
<th>Is Allowed
</th>
<th>Function</th>
</tr>
</thead>
<tbody>
#{
int i = 1;
foreach (var item in Model)
{
<tr>
<td>#i
</td>
<td>
#Html.DisplayFor(modelItem => item.LibrarySchooberryMenuDetails.MenuName)
</td>
<td>
#Html.DisplayFor(modelItem => item.MenuName)
</td>
<td>
<input type="checkbox" class="MenuMap" id="#item.MenuID" data-id="#item.MenuID"/>
</td>
<td>
<table>
#foreach (var function in item.LibrarySchooberryMenuFunctions)
{
<tr>
<td>
<input type="checkbox" class="FunctionMap" id="#function.MenuFunctionID" data-id="#function.MenuFunctionID"/>
#function.Name
<input type="hidden" value="#function.MenuID" class="menuID" />
</td>
</tr>
}
</table>
</td>
</tr>
}
}
</tbody>
</table>
</div>
</form>
</div>
Refer to my answer here;
How to append ajax result in modal with datatable
First store the initialization to a variable, be sure to put this on the top of the script or inside a $(document).ready(function(){});
var dataTable = $('#tblClassName').DataTable({});
Instead of using jquery append to the table, you have to use the .add() function from the datatable object, then .draw() for refresh;
dataTable.row.Add().draw();
UPDATE:
dataTable.row.add($(trHtml)).draw();
To clear the datatable, use .clear() .
dataTable.clear();
Use this script;
$(document).ready(function(){
var dataTable = $('#tblClassName').DataTable({
'paging': true,
'lengthChange': false,
'searching': true,
'ordering': true,
'info': true,
'autoWidth': false
});
});
$(document).on('change', '.MemberSelect', function () {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: JSON.stringify({ memberTypeID: $(".MemberSelect").val() }),
url: "#Url.Action("GetUserMenuDetails", "MenuPermission")",
success: function (data) {
var trHtml = '';
// revised //////////////////////
dataTable.clear();
/////////////////////////////////
$.each(data, function (i, item) {
trHtml = trHtml + '<tr><td></td><td>' + (item.LibrarySchooberryMenuDetails!=null? item.LibrarySchooberryMenuDetails.MenuName : "") + '</td>'
'<td>' + item.MenuName + '</td>'
'<td><input type="checkbox" class="MenuMap" id="' + item.MenuID + '" data-id="' + item.MenuID + '"/></td>'
'<td><table>';
$.each(data.LibrarySchooberryMenuFunctions, function (j, functions) {
trHtml = trHtml + '<tr><td><input type="checkbox" class="FunctionMap" id="' + functions.MenuFunctionID + '" data-id="' + functions.MenuFunctionID + '"/>'
+ functions.Name + '<input type="hidden" value="' + functions.MenuID + '" class="menuID" /></td></tr>'
});
trHtml = trHtml + '</table></td></tr>'
});
// revised //////////////////////
dataTable.row.add($(trHtml)).draw();
/////////////////////////////////
},
error: function (data) {
}
});
return false;
});
The issue I am facing is similar to this old post cascading dropdown for dynamically added row. I am using the "BeginCollectionItemCore" NuGet package to setup a set of partial views, so I have unique Id's for my controls. The problem is, I can only get the first Partial View to respond to the dropdownlist changes. The subsequent dropdownlists won't cascade. I have tried with the scripts in the partial and in the main view but both have the same end result, only the first partial will cascade. Here is my code...
Main View HTML:
#model IEnumerable<RCRTCWA.DATA.DAL.tbl_RCRTimeCards>
#{
ViewBag.Title = "Index";
}
<h2>Time Card</h2>
#using (Html.BeginForm())
{
<div id="TimeCardLines">
#foreach (var item in Model)
{
Html.RenderPartial("_TimeCardRow", item);
}
</div>
}
#Html.ActionLink("Add more time...", "_TimeCardRow", new { ViewContext.FormContext.FormId }, new { id = "addTime"})
Main View Script:
<script>
$(document).ready(function () {
debugger;
$("#addTime").click(function () {
$.ajax({
url: this.href,
cache: false,
success: function (html) { $("#TimeCardLines").append(html); }
});
return false;
});
//var index = "";
$(".timecardrow").focusin(function () {
var ti = $(this).find("[name='timecardrows.index']");
var index = ti.val();
$("#timecardrows_" + index + "__HRS_EndTime").timepicker({
defaultTime: 'now',
minTime: '6:00am',
maxTime: '7:00pm'
});
$("#timecardrows_" + index + "__HRS_StartTime").timepicker({
defaultTime: 'now',
minTime: '6:00am',
maxTime: '7:00pm'
});
//$("#.Line_TimeCard").ajaxSuccess(function () {
// $.getJSON("/TimeCard/AddTimeCardRow/", $("#.Success").html(data).show());
//});
$("#timecardrows_" + index + "__WOTicketNo").change(function () {
var tktid = $(this).val();
$("#timecardrows_" + index + "__WOTicketRepLineNo").empty();
$.ajax({
url: "/TimeCard/GetRepairLines/",
data: { ticket: tktid },
cache: false,
type: "POST",
success: function (data) {
$.each(data, function (i, data) {
$("#timecardrows_" + index + "__WOTicketRepLineNo").append('<option value="' + data.Value + '">' + data.Text + '</option>');
});
},
error: function (response) {
alert("Error : " + response);
}
});
GetCarNumber(tktid);
});
$("#timecardrows_" + index + "__WOTicketRepLineNo").change(function () {
var line = $("#timecardrows_" + index + "__WOTicketRepLineNo").val();
$("#timecardrows_" + index + "__WOTicketLaborLineNo").empty();
$.ajax({
url: "/TimeCard/GetLineDetails/",
data: { lineid: line },
cache: false,
type: "POST",
success: function (data) {
$.each(data, function (i, data) {
$("#timecardrows_" + index + "__WOTicketLaborLineNo").append('<option value="' + data.Value + '">' + data.Text + '</option>');
});
},
error: function (response) {
alert("error : " + response);
}
});
return false;
}).change();
function GetCarNumber(ticket) {
$.ajax({
url: "/TimeCard/GetCarNumber/",
data: { ticket: ticket },
cache: false,
type: "POST",
success: function (data) {
$("#timecardrows_" + index + "carNo").html(data).show();
},
error: function (response) {
alert("Error : " + response);
}
});
}
});
});
</script>
Partial View HTML:
#using HtmlHelpers.BeginCollectionItem
#model RCRTCWA.DATA.DAL.tbl_RCRTimeCards
<div class="timecardrow">
#using (Html.BeginCollectionItem("timecardrows"))
{
<div class="form-horizontal">
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<table>
<tr>
<th class="col-sm-1">
Ticket Number
</th>
<th class="col-sm-1">
Car Number
</th>
<th class="col-sm-1">
Repair Line / Description
</th>
<th class="col-sm-1">
Labor Line / Description
</th>
<th class="col-sm-1">
Start Time
</th>
<th class="col-sm-1">
End Time
</th>
<th class="col-sm-1">
Line Complete?
</th>
</tr>
<tr>
<td class="form-group">
<div class="col-sm-1 tickets">
#Html.DropDownListFor(model => model.WOTicketNo, (SelectList)ViewData["TicketsList"], "Select one...", new { #class = "ticketddl" } )
#Html.ValidationMessageFor(model => model.WOTicketNo, "", new { #class = "text-danger" })
</div>
</td>
<td class="form-group">
<div class="col-sm-1 cars">
<div id="carNo"></div>
#Html.HiddenFor(model => model.CarNo)
#Html.ValidationMessageFor(model => model.CarNo, "", new { #class = "text-danger" })
</div>
</td>
<td class="form-group">
<div class="col-sm-1 replines">
#Html.DropDownListFor(model => model.WOTicketRepLineNo, new SelectList(string.Empty, "Value", "Text"), "Select one...", new { #class = "repairddl" })
</div>
</td>
<td class="form-group">
<div class="col-sm-1 laborlines">
#Html.DropDownListFor(model => model.WOTicketLaborLineNo, new SelectList(string.Empty, "Value", "Text"), "Select one...", new { #class = "lablineddl" })
</div>
</td>
<td class="form-group">
<div class="col-sm-1 starttime">
#Html.EditorFor(model => model.HRS_StartTime, new { #class = "start" })
#Html.ValidationMessageFor(model => model.HRS_StartTime, "", new { #class = "text-danger" })
</div>
</td>
<td class="form-group">
<div class="col-sm-1 endtime">
#Html.EditorFor(model => model.HRS_EndTime, new { #class = "end" })
#Html.ValidationMessageFor(model => model.HRS_EndTime, "", new { #class = "text-danger" })
</div>
</td>
<td class="form-group">
<div class="col-sm-1 completed">
#Html.EditorFor(model => model.Completed)
#Html.ValidationMessageFor(model => model.Completed, "", new { #class = "text-danger" })
</div>
</td>
#*<td class="form-group">
<div class="col-sm-1">
<input type="submit" value="Submit Line" class="btn btn-default" />
</div>
<div id="success" class="alert-danger">
</div>
</td>*#
</tr>
</table>
</div>
}
</div>
Currently I have the script in the Main View, and have attempted to get the index part of the partial view's controls when the user interacts with the partial view. I need a better way to handle this, and need to get the cascading dropdownlist's working properly.
I would prefer to have the script in the Main View (if possible) to keep things simpler.
You do not need to bind the change event handler on dropdown using concatenated id strings, which is prone to errors (typos etc) and not easily readable/maintainable. For your cascading dropdown scenario, all you care about is updating the second select element in the same row. jQuery has some handy methods like closest and find which will make our life easier.
For making it easier for future readers, I am going to assume that your first SELECT element is to render a list of countries and has a css class "countrySelect" and second one is for the states of selected country and has the css class "statesSelect" and both are in the same table row (<tr>).
When you bind the change event, make sure you use jQuery on to do so. This will enable the binding for current and future elements in the DOM .
$("#TimeCardLines").on("change","SELECT.countrySelect",function (e) {
var _this = $(this);
var v = _this.val();
// to do :Change below url variable value as needed for your code
var urlToGetSecondDropDownData = "/Home/GetStates?countryId"+v;
$.getJSON(urlToGetSecondDropDownData,
function (res) {
var items = "";
$.each(res,
function(index, item) {
items += "<option value='" + item.Value + "'>"
+ item.Text + "</option>";
});
_this.closest("tr") // Get the same table row
.find("SELECT.statesSelect") // Find the second dropdown
.html(items); // update the content of it
});
});
Assuming you have a GetStates action method which accepts a countryId param and return the corresponding states as a list of SelectListItem ( the data needed to build the second dropdown). Something like below,
public ActionResult GetStates(int countryId)
{
var states =db.States.Where(f => f.CountryId == countryId)
.Select(f => new SelectListItem() { Value = f.Id.ToString(),
Text = f.Name})
.ToList();
return Json(states, JsonRequestBehavior.AllowGet);
}
//first dropdowlist change event
$("#countryId").change(function () {
var id = this.value;
if (id == "") {
id = "0";
}
$.get('/Home/GetStates/' + id,
function (data) {
$('#stateId').find('option').remove()
$(data).each(
function (index, item) {
$('#stateId').append('<option value="' + item.Value + '">' + item.Text + '</option>')
});
}
);
});
public ActionResult GetStates(int id)
{
List<SelectListItem> StatesList= new List<SelectListItem>();
StatesList.Add(new SelectListItem { Text = "---Select State---", Value = "0" });
var getStateCollection= (from f in _ent.States
where f.CountryId == id && f.DeletedDate == null
select new { f.Id, f.Name}).ToList();
foreach (var item in getStateCollection)
{
StatesList.Add(new SelectListItem { Text = item.Name.ToString(), Value = item.Id.ToString() });
}
return Json(StatesList, JsonRequestBehavior.AllowGet);
}
Hi I have four fields in my view CustomerName, ContactPerson, Email, MobileNo
CustomerName and ContactPerson are Cascading Dropdown, and Email and MobileNo are textboxes.
If I select the CustomerName, related ContactPerson will load automatically in ContactPerson dropdown.
If I select the Contactperson the Contact person related Email and PhoneNo will load automatically in Email and PhoneNo textbox. This works as expected.
Now all are working fine the two cascading drop down are working fine now my issue is if i select the contact person the contact person related Email and phone no is not displaying in that appropriate text boxes.
My Controller Code:
public JsonResult GetCustomers()
{
return Json(db.Customers.ToList(), JsonRequestBehavior.AllowGet);
}
public JsonResult GetContactPersobByCustomerId(string customerId)
{
Guid Id = Guid.Parse(customerId);
var customercontacts = (from a in db.CustomerContacts where a.CustomerID == Id select a);
return Json(customercontacts, JsonRequestBehavior.AllowGet);
}
public JsonResult GetPhoneNoByContactPersonID(Guid CustomerContactId)
{
var resultMobileNumber = string.Empty;
var resultEmail = string.Empty;
var ContactID = db.CustomerContacts.Where(i => i.CustomerContactID == CustomerContactId).Select(i => i.ContactID).FirstOrDefault();
if (ContactID != null)
{
var contact = (from p in db.Contacts where p.ContactID == ContactID select p).FirstOrDefault();
if (contact != null)
{
if (string.IsNullOrEmpty(contact.Mobile1) == false)
{
resultMobileNumber = contact.Mobile1;
}
else if (string.IsNullOrEmpty(contact.Mobile2) == false)
{
resultMobileNumber = contact.Mobile2;
}
}
if (contact != null)
{
if (string.IsNullOrEmpty(contact.Email1) == false)
{
resultEmail = contact.Email1;
}
else if (string.IsNullOrEmpty(contact.Email2) == false)
{
resultEmail = contact.Email2;
}
}
}
var details = new { success = true, email = resultEmail, mobileno = resultMobileNumber };
return Json(details, JsonRequestBehavior.AllowGet);
}
View Code:
#Html.Label("Customer Name", new { #class = "control-label" })
#Html.DropDownListFor(model => model.CustomerID, new SelectList(string.Empty, "Value", "Text"), "Please select a Customer", new { #class = "form-control required", type = "text" })
#Html.Label("Contact Person", new { #class = "control-label" })
#Html.DropDownListFor(model => model.CustomerContactID, new SelectList(string.Empty, "Value", "Text"), "Please select a ContactPerson", new { #class = "form-control", type = "text", id = "CustomerContactID" })
#Html.LabelFor(model => model.MobileNo, new { #class = "control-label" })
#Html.TextBoxFor(model => model.MobileNo, new { #class = "form-control", type = "text",disabled = "disabled", #readonly = "readonly" })
#Html.ValidationMessageFor(model => model.MobileNo)
#Html.LabelFor(model => model.Email, new { #class = "control-label" })
#Html.TextBoxFor(model => model.Email, new { #class = "form-control", type = "text" ,disabled = "disabled", #readonly = "readonly" })
#Html.ValidationMessageFor(model => model.Email)
J-query Code
<script src="~/Scripts/jquery-ui-1.11.0.js"></script>
<script>
$(function () {
$.ajax(
'#Url.Action("GetCustomers", "VisitorsForm")',{
type: "GET",
datatype: "Json",
success: function (data) {
$.each(data, function (index, value) {
$('#CustomerID').append('<option value="' + value.CustomerID + '">' + value.DisplayName + '</option>');
});
}
});
$('#CustomerID').change(function () {
$('#CustomerContactID').empty();
$.ajax(
'#Url.Action("GetContactPersobByCustomerId", "VisitorsForm")',{
type: "POST",
datatype: "Json",
data: { CustomerID: $('#CustomerID').val() },
success: function (data) {
$('#CustomerContactID').append($('<option></option>').val('').text('Please select'));
$.each(data, function (index, value) {
$('#CustomerContactID').append('<option value="' + value.CustomerContactID + '">' + value.ContactReference + '</option>');
});
}
});
});
});
$("#CustomerContactID").change(function () {
alert("hhh");
debugger;
$.ajax(
'#Url.Action("GetPhoneNoByContactPersonID", "VisitorsForm")',{
type: "GET",
dataType: "html",
async: false,
data: { CustomerContactID: $("#CustomerContactID").val()
},
error: function (ex) {
alert('Failed to retrieve Email.' + ex);
},
beforeSend: function () {
},
success: function (data) {
$("#Email").val(data.email);
$("#MobileNo").val(data.mobileno)
alert("Success");
}
});
});
Now all are working fine when i click the contact person it come to the GetPhoneNoByContactPersonID action it calculate the values and return again to the view ans it is also visible in Network too. All are perfect but it not displaying the data in textbox. while i inspect the code it didn't show any error in console. But it shows one warning message which is mentioned below.
Now all are working fine. But i donno why it is not displaying i donno where is the issue is. I tried my level bwst to explain my issue.-please any one help me to clear this issue.
Advance Thanks
There is no id associated with.So assign an id first in TextBoxFor like this.
#Html.TextBoxFor(model => model.MobileNo, new {#id = "MobileNo", #class = "form-control", type = "text",disabled = "disabled", #readonly = "readonly" })
#Html.TextBoxFor(model => model.Email, new {#id = "Email", #class = "form-control", type = "text" ,disabled = "disabled", #readonly = "readonly" })
Now this should work
$("#Email").val(data.email);
$("#MobileNo").val(data.mobileno)
The Following is the View :
<div class="editor-label">
Select Currency :
</div>
<div class="editor-field">
#Html.DropDownList("CurrencyId", new SelectList(ViewBag.CurrencyId, "Value", "Text"))
</div><div class="editor-label">
Select GameType :
</div>
<div class="editor-field">
#Html.DropDownList("GameTypeId", new SelectList(ViewBag.GameTypeId, "Value", "Text"), new { style = "width:100px" })
#Html.ValidationMessageFor(model => model.GameTypeId)
</div>
<div class="editor-label">
Select Category :
</div>
<div class="editor-field">
#Html.DropDownList("CategoryByGameType", Enumerable.Empty<SelectListItem>(), "Select Category")
#Html.ValidationMessageFor(model => model.CategoryId)
</div>
The following is Controller:-
public ActionResult Create()
{
List<Currency> objCurrency = new List<Currency>();
objCurrency = db.Currencies.ToList();
List<SelectListItem> listItems = new List<SelectListItem>();
listItems.Add(new SelectListItem()
{
Value = "0",
Text = "Select Currency"
});
foreach (Currency item_Currency in objCurrency)
{
listItems.Add(new SelectListItem()
{
Value = item_Currency.CurrencyId.ToString(),
Text = item_Currency.CurrencyName
});
}
ViewBag.CurrencyId = new SelectList(listItems, "Value", "Text");
List<GameType> objgametype = objGameByGameType.GetDistinctGameTypeID();
List<SelectListItem> listItems_1 = new List<SelectListItem>();
listItems_1.Add(new SelectListItem()
{
Value = "0",
Text = "Select Game Type"
});
foreach (GameType item_GameType in objgametype)
{
listItems_1.Add(new SelectListItem()
{
Value = item_GameType.GameTypeId.ToString(),
Text = item_GameType.GameTypeName
});
}
ViewBag.GameTypeId = new SelectList(listItems_1, "Value", "Text");
return View();
}
The following is my Jquery for i am using Casceding Dropdown
$(function () {
$("#GameTypeId").change(function () {
var theatres = "";
var gametype = "";
var mytestvar = "";
var gametypeid = $(this).val();
mytestvar += "<option value= -1 >Select Category</option>";
$.getJSON("#Url.Action("GetCategoryByGameType", "GameCombination")?gametypeid=" + gametypeid, function (data) {
$.each(data, function (index, gametype) {
// alert("<option value='" + gametype.Value + "'>" + gametype.Text + "</option>");
mytestvar += "<option value='" + gametype.Value + "'>" + gametype.Text + "</option>";
});
//alert(mytestvar);
$("#CategoryByGameType").html(mytestvar);
$("#GamebyCategory").html("<option value=0>Select Game</option>");
$("#LimitVariantByGameByGameType").html("<option value=0>Select Limit Variant</option>");
$("#StakeCategory").html("<option value=0>Select Stake Category</option>");
$("#StakeBuyInByStakeCategory").html("<option value=0>Select Stake Buy In By Stake Category</option>");
});
});
});
While submit data i am not able to get back the dropdown value if Error come on creation
Echo of what Andras said, you can't use razor syntax in a .js file if that's happening.
Also you should get familiar with your debugging tools, what browser are you using? Most have a nice set of developer tools (some have them built in) where you can inspect the page and the request sent out when you submit the form.
You could interactively use jquery in the console of your browser to look around also.
You don't show your post create method, perhaps it is related to that code?
This should give you an idea of what you can do.
I would suggest that you move the ajax into its own function and the $.each into its own function and call the $.each function out of the ajax function and the ajax function out of the main function.
$(function () {
$("#GameTypeId").change(function () {
var theatres = "";
var gametype = "";
var mytestvar = "";
var gametypeid = $(this).val();
mytestvar += "<option value= -1 >Select Category</option>";
$.ajax({
url: '/GameCombination/GetCategoryByGameType',
type: 'GET',
data: { "gametypeid": gametypeid},
dataType: 'json',
success: function (data) {
$.each(data, function (index, gametype) {
// alert("<option value='" + gametype.Value + "'>" + gametype.Text + "</option>");
mytestvar += "<option value='" + gametype.Value + "'>" + gametype.Text + "</option>";
});
//alert(mytestvar);
$("#CategoryByGameType").html(mytestvar);
$("#GamebyCategory").html("<option value=0>Select Game</option>");
$("#LimitVariantByGameByGameType").html("<option value=0>Select Limit Variant</option>");
$("#StakeCategory").html("<option value=0>Select Stake Category</option>");
$("#StakeBuyInByStakeCategory").html("<option value=0>Select Stake Buy In By Stake Category</option>");
},
error: function (error) {
alert(error.toString());
}
});
});
});
You have to create a object for dropdownlist in View.cs and then assign the value. After that when u try to get the dropdown values u have to use the ViewBag title object name and then the dropdownlist value.
Below code specifies for the radiobutton. You can alter it for dropdown
#model MVC_Compiler.Models.UserProgram
#{
ViewBag.Title = "UserProgram";
}
<table style="background-color: #FBF9EF;">
<colgroup>
<col style="width: 20%;">
<col style="width: 80%;">
</colgroup>
<tr>
<td style="vertical-align: text-top">
#Html.RadioButtonFor(up => up.Language, "C")C<br />
#Html.RadioButtonFor(up => up.Language, "C++")C++<br />
#Html.RadioButtonFor(up => up.Language, "C#")C#<br />
#Html.RadioButtonFor(up => up.Language, "VB")VB<br />
#Html.RadioButtonFor(up => up.Language, "Java")Java<br />
#Html.RadioButtonFor(up => up.Language, "Perl")Perl<br />
#Html.HiddenFor(up => up.Language, new { #id = "Select_Language" })
#Html.HiddenFor(up => up.UserName, new { #id = "UserName" })
</td>
Then in Models you can get the radio button value by following way:
userProgram.Language
where userProgram is ViewBag Title.