MVC controller query - c#

Following is my cascasde dropdown list query. Countries list loading up but non of the states loading up in my dropdown list. if someone can help me to rectify the query please.
public ActionResult CountryList()
{
var countries = db.Countries.OrderBy(x=>x.CountryName).ToList();
// IQueryable countries = Country.GetCountries();
if (HttpContext.Request.IsAjaxRequest())
{
return Json(new SelectList(
countries,
"CountryID",
"CountryName"), JsonRequestBehavior.AllowGet
);
}
return View(countries);
}
public ActionResult StateList(int CountryID)
{
IQueryable <State> states= db.States. Where(x => x.CountryID == CountryID);
if (HttpContext.Request.IsAjaxRequest())
return Json(new SelectList(
states,
"StateID",
"StateName"), JsonRequestBehavior.AllowGet
);
return View(states);
}
following is the View file also containg java script:
#section scripts {
<script type="text/javascript">
$(function () {
$.getJSON("/Dropdown/Countries/List",function (data) {
var items = "<option>---------------------</option>";
$.each(data, function (i, country) {
items += "<option value='" + country.Value + "'>" + country.Text + "</option>";
});
$("#Countries").html(items);
});
$("#Countries").change(function () {
$.getJSON("/Dropdown/States/List/" + $("#Countries > option:selected").attr("value"), function (data) {
var items = "<option>---------------------</option>";
$.each(data, function (i, state) {
items += "<option value='" + state.Value + "'>" + state.Text + "</option>";
});
$("#States").html(items);
});
});
});
</script>
}
<h1>#ViewBag.Title</h1>
#using (Html.BeginForm())
{
<label for="Countries">Countries</label>
<select id="Countries" name="Countries"></select>
<br /><br />
<label for="States">States</label>
<select id="States" name="States"></select>
<br /><br />
<input type="submit" value="Submit" />
}

First of all, your action method name is StateList which expects a parameter named CountryID. But your code is not making a call to your StateList action method with such a querystring param. So fix that.
$("#Countries").change(function () {
$.getJSON("#Url.Action("StateList","Home")?CountryID=" +
$("#Countries").val(), function (data) {
var items = "<option>---------------------</option>";
$.each(data, function (i, state) {
items += "<option value='" + state.Value + "'>" + state.Text + "</option>";
});
$("#States").html(items);
});
});
I also used #Url.Action helper method to get the correct url to the action method with the assumption that your StateList action method belongs to HomeController. Update the parameter according to your real controller name as needed.
Now, In your action method, you should not try to return the IQueryable collection, you may simply project the data to a list of SelectListItem and return that.
public ActionResult StateList(int CountryID)
{
var states = db.States.Where(x => x.CountrId==CountryID).ToList();
//this ToList() call copies the data to a new list variable.
var stateOptions = states.Select(f => new SelectListItem {
Value = f.StateID.ToString(),
Text = f.StateName }
).ToList();
if (HttpContext.Request.IsAjaxRequest())
return Json(stateOptions, JsonRequestBehavior.AllowGet);
return View(states);
}

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);
}

Populate textbox with related data from dropdownlist selected index

I have a working cascading dropdown list, whereby, once I select one value, it populates the second dropdown by use of JSON. I don't know how to pass this second dropdownlist index (and also whenever it is changed) to my controller to display corresponding data from my model.
My json dropdownlist is as follows
$(function () {
$('#VoyageDivID').hide();
$('#tabsDiv').hide();
$('#Vessel_ID').change(function () {
var URL = $('#VesselVoyageFormID').data('voyagelistaction')+'/' + $('#Vessel_ID').val();
$.getJSON(URL, function (data) {
var items = "";
$.each(data, function (i, voyage) {
items += "<option value='" + voyage.Value + "'>" + voyage.Text + "</option>";
});
$('#Voyage_ID').html(items);
$('#VoyageDivID').show();
$('#tabsDiv').show();
});
});
$('#Voyage_ID').change(function () {
$('#tabsDiv').show();
//need to show the related data here whenever the dropdownlist is changed
});
});
VIEW
<div id="tabsDiv">
<div class="editor-label">
XYZ
</div>
<div class="editor-field">
#Html.EditorFor(model => model.XYZ)
</div>
</div>
CONTROLLER
public ActionResult VoyageList(int ID)
{
// int voyageID = ID;
var voyages = from s in db.EXAMPLE.OrderByDescending(i => i.Voyage_ID).ToList()
where s.Vessel_ID == ID
select s;
if (HttpContext.Request.IsAjaxRequest())//only if it comes from list
return Json(new SelectList(
voyages.ToArray(),
"Voyage_ID",
"Voyage_ID")
, JsonRequestBehavior.AllowGet);
return RedirectToAction("Index");
}

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.

using getJSON to display list of customers (name, address) in MVC

I'm trying to get list of customers (name and address) when one types the country name in textbox and clicks the button.
Here is the view:
<p>
Enter country name #Html.TextBox("Country")
<input type="submit" id="GetCustomers" value="Submit"/>
</p>
Here is the JSON call:
<script type="text/jscript">
$('#GetCustomers').click(function () {
//var url = "/Home/CustomerList";
//var Country = $('#Country').val();
//$.getJSON(url, { input: Country }, function (data) {
$.getJSON('/Home/CustomerList/' + $('#Country').val(), function (data) {
var items = '<table><tr><th>Name</th><th>Address</th></tr>';
$.each(data, function (i, country) {
items += "<tr><td>" + country.ContactName + "</td><td>" + country.Address + "</td></tr>";
});
items += "</table>";
$('#rData').html(items);
});
})
</script>
Here is the controller:
public JsonResult CustomerList(string Id)
{
var result = from r in db.Customers
where r.Country == Id
select r;
return Json(result);
}
My problems are:
i) When I'm using following
var url = "/Home/CustomerList";
var Country = $('#Country').val();
$.getJSON(url, { input: Country }, function (data) {
It is not passing prameter to CustomerList method, however following works fine
$.getJSON('/Home/CustomerList/' + $('#Country').val(), function (data) {
ii) When I'm using following JSON
$.getJSON('/Home/CustomerList/' + $('#Country').val(), function (data) {
and then following CustomerList method
public JsonResult CustomerList(string Id)
{
var result = from r in db.Customers
where r.Country == Id
select r;
return Json(result);
}
It works fine when I use 'string Id' but when I use 'string country' and then 'where r.Country == country', not works.
iii) Is this correct way to work with response, not working
var items = '<table><tr><th>Name</th><th>Address</th></tr>';
$.each(data, function (i, country) {
items += "<tr><td>" + country.ContactName + "</td><td>" + country.Address + "</td></tr>";
});
items += "</table>";
$('#rData').html(items);
Any help appreciated.
Try this
$('#GetCustomers').click(function () {
//var url = "/Home/CustomerList";
//var Country = $('#Country').val();
//$.getJSON(url, { input: Country }, function (data) {
$.getJSON('/Home/CustomerList/' + $('#Country').val(), function (data) {
var items = '<table><tr><th>Name</th><th>Address</th></tr>';
$.each(data, function (i, country) {
items += "<tr><td>" + country.ContactName + "</td><td>" + country.Address + "</td></tr>";
});
items += "</table>";
$('#rData').html(items);
},'json');
});
Here is the docs http://api.jquery.com/jQuery.getJSON/

Categories