Cascading Dropdownlist is not working with Jquery - c#

I have to do one dropdownlist and one listbox. When I select a value in dropdownlist, the listbox has to change. I'm trying to do this with Jquery, because I'm using MVC. But when I select the ID in the first dropdownlist, nothing happens. My code:
View (Jquery):
<script type="text/javascript">
$(document).ready(function () {
$('#IDCONCESSAO').change(function () {
$.ajax({
url: '/Localidades/LocalidadesMunicipio',
type: 'POST',
data: { ConcessaoId: $(this).val() },
datatype: 'json',
success: function (data) {
var options = '';
$.each(data, function () {
options += '<option value="' + this.IdLocalidade + '">' + this.NomeLocalidades + '</option>';
});
$('#IDLOCALIDADE').prop('disabled', false).html(options);
}
});
});
});
</script>
Dropdownlist and listbox part:
<%: Html.DropDownListFor(model => model.SINCO_CONCESSAO, new SelectList(ViewBag.IDCONCESSAO, "Id", "Nome"), new { #class = "select", style = "width: 250px;" }) %>
</div>
<div class="editor-label" style="font-weight: bold">
Localidades:
</div>
<div class="editor-field" id="Localidades">
<%: Html.ListBoxFor(m => m.SelectedItemIds, Model.ItemChoices, new { id = "IDLOCALIDADE", size = "10" })%>
</div>
The action that do the cascade:
[HttpPost]
public ActionResult LocalidadesMunicipio(int ConcessaoID)
{
var Localidades = (from s in db.LOCALIDADES_VIEW
join c in db.SINCO_CONCESSAO.ToList() on s.ID_MUNICIPIO equals c.IDMUNICIPIO
where c.IDCONCESSAO == ConcessaoID
select new
{
idLocalidade = s.ID_LOCALIDADE,
NomeLocalidades = s.NOME_LOCALIDADE
}).ToArray();
return Json(Localidades);
}
Controller:
[Authorize(Roles = "ADMINISTRADOR")]
public ActionResult Create(SINCO_LOCALIDADE_CONCESSAO model)
{
//Here I populate my dropdownlist
ViewBag.IDCONCESSAO = from p in db.SINCO_CONCESSAO.ToList()
join c in db.MUNICIPIOS_VIEW.ToList() on p.IDMUNICIPIO equals c.ID_MUNICIPIO
join d in db.SINCO_TIPO_CONCESSAO.ToList() on p.IDTIPOCONCESSAO equals d.IDTIPOCONCESSAO
select new
{
Id = p.IDCONCESSAO,
Nome = p.IDCONCESSAO + " - " + c.NOME_MUNICIPIO + " - " + d.DSTIPOCONCESSAO
};
//Here I populate my listbox
PopulateItemLocalidades(model);
return View(model);
}
I can't see what is wrong T_T
What I am missing?

The first drop down most likely has an ID of SINCO_CONCESSAO, by the name of the property it was created for. And you are referring to something different in your script.
To fix this, either specify a different ID in jQuery:
$('#SINCO_CONCESSAO').ajax ...
or set an ID for a dropdown in View:
<%: Html.DropDownListFor(model => model.SINCO_CONCESSAO, ...
, new { id = "IDCONCESSAO" ... }) %>

Related

C# Mvc Web Api Cascading List

This is my controller.
public class DokuzasController : Controller
{
public ActionResult AddOrEdit()
{
DersViewModel model = new DersViewModel();
schoolEntities sc = new schoolEntities();
List<ders> dersList = sc.ders.OrderBy(f => f.Ders1).ToList();
model.DersList = (from s in dersList
select new SelectListItem
{
Text = s.Ders1,
Value = s.DersID.ToString()
}).ToList();
model.DersList.Insert(0, new SelectListItem { Value = "", Text = "Select"});
return View(model);
}
[HttpPost]
public ActionResult AddOrEdit(DersViewModel model)
{
if (model.LectureId == 0)
{
HttpResponseMessage response = GlobalVariables.LecturesClient.PostAsJsonAsync("dokuzas", model).Result;
TempData["SuccessMessage"] = "Saved.";
}
else
{
HttpResponseMessage response = GlobalVariables.LecturesClient.PutAsJsonAsync("dokuzas/" + model.LectureId, model).Result;
TempData["SuccessMessage"] = "Successful.";
}
return RedirectToAction("Index");
}
[HttpPost]
public JsonResult SaatList(int id)
{
schoolEntities sc = new schoolEntities();
List<saat> saatList = sc.saat.Where(f => f.DersID == id).OrderBy(f => f.Saat1).ToList();
List<SelectListItem> itemList = (from i in saatList
select
new SelectListItem
{
Value = i.SaatID.ToString(),
Text = i.Saat1
}).ToList();
return Json(itemList, JsonRequestBehavior.AllowGet);
}
}
And this is my AddOrEdit file.
#model Mvc.Models.DersViewModel
#{
ViewBag.Title = "AddOrEdit";
}
#using (Html.BeginForm("AddOrEdit", "Dokuzas", FormMethod.Post))
{
#Html.DropDownListFor(m => m.DersID, Model.DersList)
<br /><br />
#Html.DropDownListFor(m => m.SaatID, Model.SaatList)
<br />
<input type="submit" value="Kaydet" class="btn button" />
}
#section scripts{
<script type="text/javascript">
$(document).ready(function () {
$("#DersID").change(function () {
var id = $(this).val();
var saatList = $("#SaatID");
saatList.empty();
$.ajax({
url: '/Dokuzas/SaatList',
type: 'POST',
dataType: 'json',
data: { 'id': id },
success: function (data) {
$.each(data, function (index, option) {
saatList.append('<option value=' + option.Value + '>'
+ option.Text + '</option>')
});
}
});
});
});
</script>
}
I have a table and this table contains Dersadi and Dagilimi properties. I wanted to create a cascading list and add to table from this list from DersList to Dersadi and from SaatList to Dagilimi. But i choose items and select submit button i can submit it but it added null to the table. It did not add what i choose from the list. How can i fix this?
in the view, you can use the DropDownList helper method to render the SELECT element with the data we set to the Model.DersList. We will also add our second dropdown as well.
#using (Html.BeginForm("AddOrEdit", "Dokuzas", FormMethod.Post))
{
#Html.DropDownList("DersID", Model.DersList as SelectList)
<select name="id" id="SaatID" data-url="#Url.Action("SaatList","Home")">
<br />
<input type="submit" value="Kaydet" class="btn button" />
}
<script type="text/javascript">
$(function(){
$("#DersID").change(function (e) {
var $SaatID = $("#SaatID");
var url = $SaatID.data("url")+'?id='+$(this).val();
$.getJSON(url, function (items) {
$.each(items, function (a, b) {
$vacancy.append('<option value="' + b.Value + '">' + b.Text + '</option>');
});
});
});
});
</script>

Get selectedIndex of dropdown using c# (Razor)

Is it possible to get the selectedIndex of a dropdown in a view using C# (Razor). For example, can I fill a second dropdown based off the selectedIndex of another dropdown using Razor?
#model ViewModel
<select id="dropdown1">
//Options
</select>
<select id="dropdown2">
//Options
</select>
#if(//The selectedIndex of dropdown1 == 4)
{
//Fill dropdown 2 from model
}
When using Javascript, I am a little off as well:
<script>
if (dropdown1.selectedIndex === 3)
{
#foreach (var item in Model)
{
}
}
</script>
You can do it using a ajax call when the first dropdown changes:
<script type="text/javascript">
function getDropDown2Data(id) {
$.ajax({
url: '#Url.Action("GetDropDown2Data", "YourController")',
data: { Id: id },
dataType: "json",
type: "POST",
success: function (data) {
var items = "";
$.each(data, function (i, item) {
items += "<option value=\"" + item.Name + "\">" + item.Id + "</option>";
});
$("#dropDown2").html(items);
}
});
}
$(document).ready(function () {
$("#dropDown2").change(function () {
var id = $("#dropDown2").val();
getDropDown2Data(id);
});
});
</script>
#Html.DropDownListFor(x => x.Id, new SelectList(Model.Model1, "Id", "Name"), "Select")
#Html.DropDownListFor(x => x.Id, new SelectList(Model.Model2, "Id", "Name"), "Select")
And you action:
[HttpPost]
public ActionResult GetDropDown2Data(id id)
{
//Here you get your data, ie Model2
return Json(Model2, JsonRequestBehavior.AllowGet);
}

drop down list refresh in razor

I have a drop down list which represent states and according to selected state, I need to refresh City drop down list which represent the cities in the selected state. How can I refresh the city drop down ?
Here is my code :
public class AccountController : Controller
{
public static List<SelectListItem> StateListItem()
{
var stateList = new List<SeraydarBL.Accounts.State>();
var selectListItems = new List<SelectListItem>();
stateList = SeraydarBL.Accounts.SelectStates();
foreach (var state in stateList)
{
var selectListItem = new SelectListItem();
selectListItem.Text = state.name;
selectListItem.Value = state.id.ToString();
selectListItems.Add(selectListItem);
}
return selectListItems;
}
}
here is the razor :
#using (Html.BeginForm())
{
<fieldset>
<legend>Registration Form</legend>
<ol>
<li>
//-------------------------------------------------------
var stateList = new List<SelectListItem>();
stateList = AccountController.StateListItem();
}
#Html.LabelFor(model => model.StateId)
#Html.DropDownListFor(model => model.StateId, stateList, " Select your State ...")
#Html.ValidationMessageFor(m => m.StateId)
#*HERE MUST BE THE DROP DOWN LIST OF CITIES*#
</li>
</ol>
<input type="submit" value="Register" />
</fieldset>
<script>
$('#StateId').change(function () {
});
</script>
}
You can achieve this using jquery ajax call.
<script type="text/javascript">
$(document).ready(function () {
//Dropdownlist Selectedchange event
$("#StateId").change(function () {
$("#CityId").empty();
$.ajax({
type: 'POST',
url: '#Url.Action("GetCity")',
dataType: 'json',
data: { id: $("#StateId").val() },
success: function (cities) {
$.each(cities, function (i, city) {
$("#CityId").append('<option value="' + city.Value + '">' +``});
},
error: function (ex) {
alert('Failed to retrieve states.' + ex);
}
});
return false;
})
});
</script>
refer few articles
http://www.codeproject.com/Articles/730953/Cascading-Dropdown-List-With-MVC-LINQ-to-SQL-and-A
http://www.c-sharpcorner.com/UploadFile/4d9083/creating-simple-cascading-dropdownlist-in-mvc-4-using-razor/

Multiple partial view rendering

I have three dropdownlist - Project, Sprint, Story.
Sprint dropdownlist will be binded on the basis of selected Project, Story dropdownlist will be binded on the basis of selected Sprint. On the basis of selected Story, i want to show a webgrid.
what i m doing is:
my Project dropdownlist is on the main view page, Sprint dropdownlist, and Story dropdownlist are two diferent partial views. When i select from Project, selected value is taken in jquery and passed to controller as:
$('#Project').change(function (e) {
e.preventDefault();
var selectedVal = $("#Project").val();
$.ajax({
url: "/Task/BindSprintList",
data: { projectTitle: selectedVal },
type: 'Get',
success: function (result) {
$('#ViewGrid').html(result);
},
error: function () {
alert("something seems wrong");
}
});
});
Now Sprint Dropdown list appears. When i select from Sprint, selected value is taken in jquery and passed to controller as:
$('#Sprint').change(function (e) {
e.preventDefault();
var selectedProjectVal = $("#Project").val();
var selectedSprintVal = $("#Sprint").val();
$.ajax({
url: "/Task/BindStoryList",
data: { projectTitle: selectedProjectVal, sprintTitle: selectedSprintVal },
type: 'Get',
success: function (result) {
$('#ddlStory').html(result); },
error: function (err) {
alert("something seems wrong "+ err);
}
});
});
but now Story Dropdownlist is not displaying.
MainPage.cshtml
<table>
#{
if (ViewBag.ProjectList != null)
{
<tr>
<td>
<h4>SELECT PROJECT </h4>
</td>
<td>
#Html.DropDownList("Project", new SelectList(ViewBag.ProjectList, "Value", "Text"), " -- Select -- ")
</td>
</tr>
}
if (ViewBag.SprintList != null)
{
Html.RenderPartial("PartialSprintDropDown", Model.AsEnumerable());
}
if (ViewBag.StoryList != null)
{
Html.RenderPartial("PartialStoryDropDown", Model.AsEnumerable());
}
}
</table>
PartialSprintDropDown.cshtml
<table>
<tr>
<td>
<h4>SELECT SPRINT</h4>
</td>
<td>
#Html.DropDownList("Sprint", new SelectList(ViewBag.SprintList, "Value", "Text"), " -- Select -- ")
</td>
</tr>
</table>
<script src="~/Script/Task/IndexTask.js" type="text/javascript"></script>
PartialStoryDropDown.cshtml
<div id="ddlStory">
<table>
<tr>
<td>
<h4>SELECT STORY</h4>
</td>
<td>
#Html.DropDownList("Story", new SelectList(ViewBag.StoryList, "Value", "Text"), " -- Select -- ")
</td>
</tr>
</table>
</div>
<script src="~/Script/Task/IndexTask.js" type="text/javascript"></script>
Can anyone suggest me that why Story DropdownList is not displaying. Even when i m debbuging PartialStoryDropDown.cshtml, "ViewBag.StoryList" contains data as expected, but not showing on the page.
I m containing my data in Viewbag.SprintList and Viewbag.StoryList.
SprintDropdownlist is displaying.
How to resolve this ?
BindSprintList()
public ActionResult BindSprintList(string projectTitle)
{
try
{
string Owner = Session["UserName"].ToString();
int? ProjectId = GetProjectID(projectTitle);
var ddlSprint = new List<string>();
List<SelectListItem> items = new List<SelectListItem>();
var querySprint = (from sp in entities.Sprints
where sp.Project_ID == ProjectId && sp.Sprint_Status != "Completed"
select sp).ToList();
foreach (var item in querySprint.ToList())
{
SelectListItem li = new SelectListItem
{
Value = item.Sprint_Title,
Text = item.Sprint_Title
};
items.Add(li);
}
IEnumerable<SelectListItem> List = items;
ViewBag.SprintList = new SelectList(List, "Value", "Text");
}
catch (Exception e)
{
var sw = new System.IO.StreamWriter(filename, true);
sw.WriteLine("Date :: " + DateTime.Now.ToString());
sw.WriteLine("Location :: AgileMVC >> Controllers >> TaskController.cs >> public ActionResult BindSprintList(string projectTitle)");
sw.WriteLine("Message :: " + e.Message);
sw.WriteLine(Environment.NewLine);
sw.Close();
}
return PartialView("PartialSprintDropDown", ViewBag.SprintList);
}
BindStoryList()
public ActionResult BindStoryList(string projectTitle, string sprintTitle)
{
try
{
string Owner = Session["UserName"].ToString();
int? ProjectId = GetProjectID(projectTitle);
int? SprintId = GetSprintID(ProjectId, sprintTitle);
var ddlStory = new List<string>();
List<SelectListItem> items = new List<SelectListItem>();
var queryStory = (from st in entities.Stories
join spss in entities.SprintStories on st.Story_ID equals spss.Story_ID
where spss.Sprint_ID == SprintId && spss.Project_ID == ProjectId
select st).ToList();
foreach (var item in queryStory.ToList())
{
SelectListItem li = new SelectListItem
{
Value = item.Story_Title,
Text = item.Story_Title
};
items.Add(li);
}
IEnumerable<SelectListItem> List = items;
ViewBag.StoryList = new SelectList(List, "Value", "Text");
}
catch (Exception e)
{
var sw = new System.IO.StreamWriter(filename, true);
sw.WriteLine("Date :: " + DateTime.Now.ToString());
sw.WriteLine("Location :: AgileMVC >> Controllers >> TaskController.cs >> public ActionResult BindStoryList()");
sw.WriteLine("Message :: " + e.Message);
sw.WriteLine(Environment.NewLine);
sw.Close();
}
return PartialView("PartialStoryDropDown", ViewBag.StoryList);
}
I think I see your problem - ddlStory div comes as part of result. So when you say $('#ddlStory'), it doesn't do anything since its not on the page yet.
I think in your main page, you need to have a placeholder for ddlStory and replace that placeholder's html. Something like $('#ddlStoryWrapper').html(result) where ddlStoryWrapper is just an empty div on the page.

How to get selected drop down values from Controller MVC

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.

Categories