I have two cascading dropdown first dropdown shows the list of countries and based on the selection of countries the next dropdown gets populated. The problem is that when I Select Value from DropDown the other dropdown not getting populated
#using (Html.BeginForm("Index", "Home", FormMethod.Post))
{
#Html.DropDownListFor(x => x.CountryId, Model.Countries,"SEC",null)
<br />
#Html.DropDownListFor(x => x.CityId, Model.Cities, "SEC", null)
<button>Kaydet</button>
}
<div>
COUNTRYId:#Model.CountryId
</div>
<div>
CİTYId:#Model.CityId
</div>
<script>
$('#CountryId').change(function () {
var val = $(this).val();
if (val != "" || val != -1) {
$('#CountryId option').not(":first").remove();
$.ajax({
method: "GET",
url: '#Url.Action("GetByCountryId","Home")' + "/" + val;
}).done(function (result) {
for (var i = 0; i < result.length; i++) {
var name = result[i].CityName;
var id = result[i].CityId;
var option = $('<option></option>');
option.text(name);
option.val(id);
$('#CityId').append(option);
}
})
} else {
$('#CountryId option').not(":first").remove();
}
})
</script>
public JsonResult GetByCountryId(int id)
{
var cities = Cities.GetFakeCities().Where(x => x.CountryId == id).ToList();
return Json(cities, JsonRequestBehavior.AllowGet);
}
What am I doing wrong?Could you plase help
The problem is that when I Select Value from DropDown the other
dropdown not getting populated.What am I doing wrong?
Well, in var option = $('<option></option>'); we have text and value to append items in it but you are using option.val(id); which is incorrect. In addition, your way of implementations are also very clumsy. As you are using javascript why don't you fully handle it using javascript.
Here, is the the complte example for you:
Model:
public class Country
{
public int CountryId { get; set; }
public string? CountryName { get; set; }
}
public class City
{
public int CityId { get; set; }
public string CityName { get; set; }
public int CountryId { get; set; }
}
Controller:
public class CascadingDropdownController : Controller
{
public static List<Country> ListOfCountry = new List<Country>()
{
new Country() { CountryId =101, CountryName ="INDIA", },
new Country() { CountryId =102, CountryName ="USA", },
new Country() { CountryId =103, CountryName ="UK", },
new Country() { CountryId =104, CountryName ="Canada", },
};
public static List<City> ListOfCity = new List<City>()
{
//INDIA
new City() { CountryId =101, CityId =1, CityName = "Delhi" },
new City() { CountryId =101, CityId =2, CityName = "Haydrabad" },
new City() { CountryId =101, CityId =3, CityName = "Pune" },
//USA
new City() { CountryId =102, CityId =4, CityName = "New York" },
new City() { CountryId =102, CityId =5, CityName = "Silicon Valley" },
new City() { CountryId =102, CityId =6, CityName = "Dallaus" },
//UK
new City() { CountryId =103, CityId =7, CityName = "London" },
new City() { CountryId =103, CityId =8, CityName = "Cardif" },
new City() { CountryId =103, CityId =9, CityName = "Sundarland" },
//Candada
new City() { CountryId =104, CityId =10, CityName = "Alberta" },
new City() { CountryId =104, CityId =11, CityName = "Ontario" },
new City() { CountryId =104, CityId =12, CityName = "Manitoba" },
};
public IActionResult Index()
{
return View();
}
[HttpGet]
public async Task<ActionResult> LoadCountry()
{
var country = ListOfCountry.ToList();
return Ok(country);
}
[HttpGet]
public async Task<ActionResult> GetCity(int countryId)
{
var citys = ListOfCity.Where(cId => cId.CountryId == countryId).ToList();
return Ok(citys);
}
}
View:
<div class="row">
<div class="col-lg-3"></div>
<div class="col-lg-6">
<div class="form-group">
<label class="col-md-4 control-label">Country</label>
<div class="col-md-6">
<select class="form-control" id="ddlCountry"></select><br />
</div>
</div>
<div class="form-group">
<label class="col-md-4 control-label">City</label>
<div class="col-md-6">
<select class="form-control" id="ddlCity"></select>
<br />
</div>
</div>
<br />
</div>
</div>
#section scripts {
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.2.1.min.js"></script>
<script src="https://cdn.datatables.net/1.11.3/js/jquery.dataTables.min.js"></script>
<script>
$(document).ready(function () {
var ddlCountry = $('#ddlCountry');
ddlCountry.append($("<option></option>").val('').html('Please Select Country'));
var ddlCity = $('#ddlCity');
ddlCity.append($("<option></option>").val('').html('Please Select Country First'));
$.ajax({
url: 'http://localhost:5094/CascadingDropdown/LoadCountry',
type: 'GET',
dataType: 'json',
success: function (d) {
console.log(d);
$.each(d, function (i, country) {
console.log(i);
console.log(country);
ddlCountry.append($("<option></option>").val(country.countryId).html(country.countryName));
});
},
error: function () {
alert('Error!');
}
});
//City details by country id
$("#ddlCountry").change(function () {
//alert("On ddlCountry change");
var CountryId = parseInt($(this).val());
console.log(CountryId);
if (!isNaN(CountryId)) {
var ddlCity = $('#ddlCity');
ddlCity.empty();
ddlCity.append($("<option></option>").val('').html('Please wait ...'));
$.ajax({
url: 'http://localhost:5094/CascadingDropdown/GetCity',
type: 'GET',
dataType: 'json',
data: { CountryId: CountryId },
success: function (d) {
ddlCity.empty(); // Clear the please wait
ddlCity.append($("<option></option>").val('').html('Select City'));
$.each(d, function (i, citys) {
ddlCity.append($("<option></option>").val(citys.cityId).html(citys.cityName));
});
},
error: function () {
alert('Error!');
}
});
}
});
});
</script>
}
Output:
Related
Used select2 for search but didn't work. Searching for the last two days on google but didn't find any. Thanks in advance.
Controller Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ListingDropdown.Models;
using System.Configuration;
using System.Data.SqlClient;
namespace ListingDropdown.Controllers
{
public class ListingController : Controller
{
// GET: Listing
public ActionResult Index()
{
Listing model = new Listing();
model.Country = new SelectList(PopulateDropDown("SELECT CountryId, CountryName FROM Country", "CountryName", "CountryId"), "Value", "Text");
model.State = new SelectList(PopulateDropDown("SELECT StateId, StateName FROM State", "StateName", "StateId"), "Value", "Text");
model.City = new SelectList(PopulateDropDown("SELECT CityId, CityName FROM City", "CityName", "CityId"), "Value", "Text");
return View(model);
}
[HttpPost]
public JsonResult GetStateList(string param)
{
Listing model = new Listing();
model.State = new SelectList(PopulateDropDown("SELECT StateId, StateName FROM State WHERE CountryId = '" + param + "'", "StateName", "StateId"), "Value", "Text");
return Json(model);
}
[HttpPost]
public JsonResult GetCityList(string param)
{
Listing model = new Listing();
model.City = new SelectList(PopulateDropDown("SELECT CityId, CityName FROM City WHERE StateId = '" + param + "'", "CityName", "CityId"), "Value", "Text");
return Json(model);
}
[HttpPost]
public ActionResult Index(int countryId, int stateId, int cityId)
{
Listing model = new Listing();
model.Country = new SelectList(PopulateDropDown("SELECT CountryId, CountryName FROM Country", "CountryName", "CountryId"), "Value", "Text");
model.State = new SelectList(PopulateDropDown("SELECT StateId, StateName FROM State WHERE CountryId = " + countryId, "StateName", "StateId"), "Value", "Text");
model.City = new SelectList(PopulateDropDown("SELECT CityId, CityName FROM City WHERE StateId = " + stateId, "CityName", "CityId"), "Value", "Text");
return View(model);
}
private static List<SelectListItem> PopulateDropDown(string query, string textColumn, string valueColumn)
{
List<SelectListItem> items = new List<SelectListItem>();
string constr = ConfigurationManager.ConnectionStrings["LocationManagementEntities"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand(query))
{
cmd.Connection = con;
con.Open();
using (SqlDataReader sdr = cmd.ExecuteReader())
{
while (sdr.Read())
{
items.Add(new SelectListItem
{
Text = sdr[textColumn].ToString(),
Value = sdr[valueColumn].ToString()
});
}
}
con.Close();
}
}
return items;
}
}
}
Views Code used the select2 plugin but did not work I don't why this is happening if anyone has knowledge please let me know. I also try the chosen plugin.
#model ListingDropdown.Models.Listing
#{
ViewBag.Title = "Index";
}
<h2>Location Choosing</h2>
#using (Html.BeginForm("Index", "Home", FormMethod.Post))
{
#Html.AntiForgeryToken()
#Html.DropDownListFor(m => m.CountryId, (IEnumerable<SelectListItem>)Model.Country, "Select", new { #class = "form-control" })
<br />
<br />
#Html.DropDownListFor(m => m.StateId, Enumerable.Empty<SelectListItem>(), "Select", new { #class = "form-control" })
<br />
<br />
#Html.DropDownListFor(m => m.CityId, Enumerable.Empty<SelectListItem>(), "Select", new { #class = "form-control" })
<br />
<br />
<input type="submit" value="Submit" />
}
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/select2#4.0.13/dist/css/select2.min.css" />
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/select2#4.0.13/dist/js/select2.min.js"></script>
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script type="text/javascript">
$(function () {
$("select").each(function () {
if ($(this).find("option").length <= 1) {
$(this).attr("disabled", "disabled");
}
});
$('#CountryId').change(function () {
var value = 0;
if ($(this).val() != "") {
value = $(this).val();
}
$.ajax({
type: "POST",
url: "/Listing/GetStateList",
data: '{param: "' + value + '"}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
var list = response.State;
$("#StateId").empty().append('<option selected="selected" value="0">Select</option>');
if (list != null && list.length > 0) {
$("#StateId").removeAttr("disabled");
$.each(list, function () {
$("#StateId").append($("<option></option>").val(this['Value']).html(this['Text']));
});
$("#StateId").select2();
}
},
error: function (response) {
alert(response.responseText);
}
});
});
});
$(function () {
$("select2").each(function () {
if ($(this).find("option").length <= 1) {
$(this).attr("disabled", "disabled");
}
});
$('#StateId').change(function () {
var value = 0;
if ($(this).val() != "") {
value = $(this).val();
}
$.ajax({
type: "POST",
url: "/Listing/GetCityList",
data: '{param: "' + value + '"}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
var list = response.City;
$("#CityId").empty().append('<option selected="selected" value="0">Select</option>');
if (list != null && list.length > 0) {
$("#CityId").removeAttr("disabled");
$.each(list, function () {
$("#CityId").append($("<option></option>").val(this['Value']).html(this['Text']));
});
$("#CityId").select2();
}
},
error: function (response) {
alert(response.responseText);
}
});
});
});
$(function () {
if ($('#StateId').val() == "") {
$("#CityId").prop("disabled", true);
}
if ($("#StateId").val() != "" && $("#CityId").val() != "") {
var message = "State: " + $("#StateId option:selected").text();
message += "\nCity: " + $("#CityId option:selected").text();
alert(message);
}
});
</script>
Model Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Configuration;
using System.Data.SqlClient;
namespace ListingDropdown.Models
{
public class Listing
{
public int CountryId { get; set; }
public int StateId { get; set; }
public int CityId { get; set; }
public SelectList Country { get; set; }
public SelectList State { get; set; }
public SelectList City { get; set; }
}
}
I have two controls on the page one for country and one for state. Once the country dropdown is changed I have this AJAX function that will return States or Provincese. I want to keep all the ValidationMessageFor and the selectedStateId in the control just looking to fill the drop down. there a way to add the option value for the select control? Any Help would be great.
View
<div class="col-md-6">
#Html.LabelFor(model => model.selectedStateId)
#Html.DropDownListFor(
x => x.selectedStateId,
new SelectList("","StateId", "Name"),
"-- please select a States or Provincese --",
new { id = "ddlStates", #class = "form-control" })
#Html.ValidationMessageFor(x => x.selectedCountryId, "", new { #class = "text-danger" })
</div>
js
$("#ddlCountry").change(function () {
var countryId = $(this).val();
console.log(countryId);
loadstates(countryId);
});
function loadstates(countryId) {
var strUrl = '#Url.Action("GetStates", "RequestForm")';
$.ajax({
url: strUrl,
type: "GET",
dataType: "html",
data: {countryId: countryId},
success: function (data) {
console.log(data);
$("#ddlStates").html($(data).html());
},
error: function (result) {
alert("error occured");
}
});
}
For cascading dropdown lists,we usually return a list in ajax,and put them into option,and put options to dropdownlist with append()(As Swati says).Here is a working demo:
View:
<form>
<select id="ddlCountry">
<option value="1">Country1</option>
<option value="2">Country2</option>
<option value="3">Country3</option>
</select>
<div class="col-md-6">
#Html.LabelFor(model => model.selectedStateId)
#Html.DropDownListFor(
x => x.selectedStateId,
new SelectList("", "StateId", "Name"),
"-- please select a States or Provincese --",
new { id = "ddlStates", #class = "form-control" })
#Html.ValidationMessageFor(x => x.selectedCountryId, "", new { #class = "text-danger" })
</div>
</form>
js:
$("#ddlCountry").change(function () {
var countryId = $(this).val();
console.log(countryId);
loadstates(countryId);
});
function loadstates(countryId) {
var strUrl = '#Url.Action("GetStates", "RequestForm")';
$.ajax({
url: strUrl ,
type: "GET",
data: {countryId: countryId},
success: function (data) {
$.each(data, function (index, value) {
var text1 = '<option value=' + value.stateId + '>' +
value.name+
'</option>';
$("#ddlStates").append(text1);
});
},
error: function (result) {
alert("error occured");
}
});
}
</script>
Model:
public class Address {
public int selectedStateId { get; set; }
public int selectedCountryId { get; set; }
}
public class State
{
public int StateId { get; set; }
public string Name { get; set; }
}
Action(I use fake data to test):
public List<State> GetStates(int countryId)
{
List<State> states = new List<State> { new State { StateId = 1, Name = "state1" }, new State { StateId = 2, Name = "state2" }, new State { StateId = 3, Name = "state3" } };
return states;
}
result:
I've already saw examples of that perfectly working but with two separate classes but I'm trying to do a cascading drop-down list just using a single class using ASP.NET MVC.
My class:
namespace e_Recarga.Models
{
public class Estacao
{
public int Id { get; set; }
[Required]
[StringLength(255)]
public string Distribuidora { get; set; }
[Required]
[StringLength(255)]
public string Nome { get; set; }
[Required]
[StringLength(255)]
[Display(Name = "Região")]
public string Regiao { get; set; }
[Required]
[StringLength(255)]
[Display(Name = "Localização")]
public string Localizacao { get; set; }
[Required]
[Display(Name = "Disponibilidade")]
public int Disponibilidade_Postos { get; set; }
public IEnumerable<Reserva> Reservas { get; set; }
}
}
namespace e_Recarga.Models
{
public class Reserva
{
public int Id { get; set; }
[Required]
public Utilizador Utilizador{ get; set; }
public Estacao Estacao { get; set; }
public byte EstacaoId { get; set; }
}
}
So in the controller I have everything get from the Database and returning it to the view.
public class ReservaController : Controller
{
private ApplicationDbContext _context;
public ReservaController()
{
_context = new ApplicationDbContext();
}
protected override void Dispose(bool disposing)
{
_context.Dispose();
}
public ActionResult Index()
{
var estacoes = _context.Estacoes.ToList();
var estacoesDistinct = estacoes.GroupBy(x => x.Regiao ).Select(x => x.First());
var viewModel = new NovaReservaViewModel
{
Estacoes = estacoesDistinct
};
return View(viewModel);
}
In the view in terms of HTML I have the drop-down lists already implemented, but I think I need to have a javascript to do the cascading stuff.
#model e_Recarga.ViewModels.NovaReservaViewModel
#{
ViewBag.Title = "New";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Nova Reserva</h2>
#using (Html.BeginForm("New", "Reserva"))
{
<div class="form-group">
#Html.LabelFor(e => e.Reserva.Estacao.Regiao)
#Html.DropDownListFor(e => e.Reserva.Estacao.Id, new SelectList(Model.Estacoes, "Id", "Regiao"), "Escolha a Região", new { #class = "form-control" })
<select id="regiao"></select>
</div>
<div class="form-group">
#Html.LabelFor(e => e.Reserva.Estacao.Distribuidora)
#Html.DropDownListFor(e => e.Reserva.Estacao.Id, new SelectList(Model.Estacoes, "Id", "Distribuidora"), "Escolha a Região", new { #class = "form-control" })
<select id="distribuidora"></select>
</div>
<div class="form-group">
#Html.LabelFor(e => e.Reserva.Estacao.Nome)
#Html.DropDownListFor(e => e.Reserva.Estacao.Id, new SelectList(Model.Estacoes, "Id", "Nome"), "Escolha a Estação", new { #class = "form-control" })
</div>
#Html.HiddenFor(e => e.Reserva.Estacao.Id)
<button type="submit" class="btn btn-primary">Save</button>
}
How can I do that?
I've tried the following javascript code:
#section scripts {
<script type="text/javascript">
$(document).ready(function () {
// Get a list of categories and a list of products of the first category.
$.getJSON('/home/GetRegioes', null, function (data) {
$.each(data, function () {
$('#regiao').append('<option value=' +
this.Estacao + '>' + this.Regiao + '</option>');
});
$.getJSON('/home/GetDistribuidoras', { intRegiaoId: $('#regiao').val() }, function (data) {
$.each(data, function () {
$('#distribuidora').append('<option value=' +
this.Estacao + '>' + this.Distribuidora + '</option>');
});
}).fail(function (jqXHR, textStatus, errorThrown) {
alert('Error getting products!');
});
}).fail(function (jqXHR, textStatus, errorThrown) {
alert('Error getting categories!');
});
// Dropdown list change event.
$('#regiao').change(function () {
$('#distribuidora option').remove();
$.getJSON('/home/GetRegiao', { intRegiaoId: $('#regiao').val() }, function (data) {
$.each(data, function () {
$('#distribuidora').append('<option value=' +
this.Distribuidora + '>' + this.ProductName + '</option>');
});
}).fail(function (jqXHR, textStatus, errorThrown) {
alert('Error getting products!');
});
});
});
</script>
}
I'am trying pass selected value of dropdownlist from one action (RMA) which i have my dropdownlist, to another action (ProcessRequestRMA) which i want send value of dropdownlist and than save it into database using Ajax.
beacuse of that i make instance of that viewmodel (OrdreDetails_VM) which is contains property of dropdown to another viewmodel (RMAHistory) which i want to get selected value and save into database, but when i try to save into database i get Object reference is not set to an instance of an object (under var RMA = new RMA_History). and its beacuse that property should get selected value its null . its been hours im struggling with this , but still no luck :(
Can anyone please help me or point me in the right direction :)
Thanks in advance :)
OrdreDetails_VM & RMA Action :
public class OrdreDetails_VM
{
public List<SelectListItem> RMAType { set; get; }
public int SelectedRMAType { set; get; }
}
public ActionResult RMA(OrdreDetails_VM oodvm)
{
//DDL
oodvm.RMAType = new SelectList(data.RMAType, "ID", "RMASager").ToList();
// do some another stuff
return View(oodvm);
}
RMAHistory_VM & ProcessRequestRMA :
public class RMAHistory_VM
{
public OrdreDetails_VM VM { get; set; }
public int RMAIDType { get; set; }
public string RMASager { get; set; }
public string Kundenavn { get; set; }
public string Ordrenummer { get; set; }
}
public JsonResult ProcessRequestRMA(RMAHistory_VM model)
{
var RMA = new RMA_History // its Modal
{
Kundenavn = model.Kundenavn,
Ordrenummer = model.Ordrenummer,
//Expect to get selected value
RMATypeID = model.VM.SelectedRMAType
};
db.RMA_History.Add(RMA);
db.SaveChanges();
return Json(model, JsonRequestBehavior.AllowGet);
}
//Here is RMAHistory Modal:
public class RMA_History
{
public int Id { get; set; }
public string Kundenavn { get; set; }
public string Ordrenummer { get; set; }
public int? RMATypeID { get; set; }
}
public RMA_HistoryMap()
{
//RMA_History Mapping stuff
}
View:
#model NameSpace.OrdreDetails_VM
//DropDown
#Html.DropDownListFor(s => s.SelectedRMAType, Model.RMAType, "- Select -", new { #class = "form-control", #id = "SelectedRMAType" })
<div class="row">
<div class="col-md-12">
<div class="form-group">
<label>KundeNavn</label>
<input name="Kundenavn" type="text" id="Kundenavn" class="form-control">
</div>
</div>
<div class="col-md-12">
<div class="form-group">
<label>Ordrenummer</label>
<input name="Ordrenummer" id="Ordrenummer" type="text" class="form-control" >
</div>
</div>
</div>
AJAX:
<script>
$(document).ready(function () {
$("#btn").click(function (e) {
e.preventDefault();
return myfunction();
});
function myfunction() {
var model = {
Kundenavn: $("#Kundenavn").val(),
Ordrenummer: $("#Ordrenummer").val(),
SelectedRMAType: $("#SelectedRMAType").val()
}
$.ajax({
type: 'POST',
url: "/Account/ProcessRequestRMA",
dataType: 'json',
data: {
Kundenavn: model.Kundenavn,
Ordrenummer: model.Ordrenummer,
RMATypeID: model.SelectedRMAType
},
success: function (status) {
if (status) {
status.Kundenavn = model.Kundenavn;
status.Ordrenummer = model.Ordrenummer;
status.RMATypeID = model.SelectedRMAType;
console.log("Send");
}
else {
alert("Something Wrong");
}
},
error: function () {
console.log('something went wrong - debug it!');
}
});
}
});
</script>
The main problem here is that your View is not bound to the correct ViewModel. You are saying that your view works with a OrdreDetails_VM when it in facts works with a RMAHistory_VM. Temporary data, just as the one your RMAType property represents, should either go into the same ViewModel when you have one, or as part of the ViewBag when you don't want to create one.
So, let's start by first updating RMAHistory_VM to have the required data:
public class RMAHistory_VM
{
public int SelectedRMAType { get; set; }
public string RMASager { get; set; }
public string Kundenavn { get; set; }
public string Ordrenummer { get; set; }
public List<SelectListItem> RMATypes { set; get; }
}
Then, let's throw away OrdreDetails_VM and make your view use RMAHistory_VM correctly:
#model NameSpace.RMAHistory_VM
#Html.DropDownListFor(s => s.SelectedRMAType, Model.RMATypes, "- Select -", new { #class = "form-control", #id = "SelectedRMAType" })
<div class="row">
<div class="col-md-12">
<div class="form-group">
<label>KundeNavn</label>
<input name="Kundenavn" type="text" id="Kundenavn" class="form-control">
</div>
</div>
<div class="col-md-12">
<div class="form-group">
<label>Ordrenummer</label>
<input name="Ordrenummer" id="Ordrenummer" type="text" class="form-control" >
</div>
</div>
</div>
Notice that your AJAX call also does not conform to the ViewModel structure (you are even creating an object you are not using), so you have to update it accordingly:
function myfunction() {
var model = {
Kundenavn: $("#Kundenavn").val(),
Ordrenummer: $("#Ordrenummer").val(),
SelectedRMAType: $("#SelectedRMAType").val()
};
$.ajax({
type: 'POST',
url: "/Account/ProcessRequestRMA",
dataType: 'json',
data: model,
success: function (status) {
if (status) {
status.Kundenavn = model.Kundenavn;
status.Ordrenummer = model.Ordrenummer;
status.RMATypeID = model.SelectedRMAType;
console.log("Send");
}
else {
alert("Something Wrong");
}
},
error: function () {
console.log('something went wrong - debug it!');
}
});
};
And finally update the Action so that it loads ViewBag.RMATypes:
public ActionResult RMA()
{
//DDL
var model = new RMAHistory_VM
{
RMATypes = new SelectList(data.RMAType, "ID", "RMASager").ToList();
};
// do some another stuff
return View(model);
}
You will then have to update how you process the request to match the new ViewModel structure:
public JsonResult ProcessRequestRMA(RMAHistory_VM model)
{
var RMA = new RMA_History // its Modal
{
Kundenavn = model.Kundenavn,
Ordrenummer = model.Ordrenummer,
RMATypeID = model.SelectedRMAType
};
db.RMA_History.Add(RMA);
db.SaveChanges();
return Json(model, JsonRequestBehavior.AllowGet);
}
I will start by saying that I am very new to asp.net MVC, but have a project that i need to complete. That being said, any help is greatly appreciated.
I have two cascading dropdown lists created and populating with MVC, LINQ to SQL and Ajax that i need the selections brought into my controller. I am trying to simply create and send an email with my form data in the body and have been stuck for some time. The Javascript returns the Id number from the database, but i need the "StateName and "CountyName" that is associated with the Id rather than just the Id. For a reference, this is the method that I used to create what I have now, but there was no explanation on how to submit the selections.
http://www.codeproject.com/Articles/730953/Cascading-Dropdown-List-With-MVC-LINQ-to-SQL-and-A
Here is my Controller
public class AddressController : Controller
{
private IAddressRepository _repository;
public AddressController() : this(new AddressRepository())
{
}
public AddressController(IAddressRepository repository)
{
_repository = repository;
}
public ActionResult Index()
{
AddressModel model = new AddressModel();
model.AvailableUSStates.Add(new SelectListItem { Text = "-Please select-", Value = "Selects items" });
var usstates = _repository.GetAllUSStates();
foreach (var usstate in usstates)
{
model.AvailableUSStates.Add(new SelectListItem()
{
Text = usstate.USStateName,
Value = usstate.USStateID.ToString()
});
}
return View(model);
}
[AcceptVerbs(HttpVerbs.Get)]
public ActionResult GetCountiesByUSStateID(string USStateID)
{
if (string.IsNullOrEmpty(USStateID))
{
throw new ArgumentNullException("USStateID");
}
int id = 0;
bool isValid = Int32.TryParse(USStateID, out id);
var counties = _repository.GetAllCountiesByUSStateID(id);
var result = (from s in counties
select new
{
id = s.CountyID,
name = s.CountyName
}).ToList();
return Json(result, JsonRequestBehavior.AllowGet);
}
[HttpPost]
public ContentResult SimplePost(string submittedState)
{
string result = string.Format(submittedState);
return new ContentResult { Content = result };
}
[AcceptVerbs(HttpVerbs.Post)]
public async Task<ActionResult> Index([Bind(Include = "USStateName, CountyName")] AddressModel addressModel)
{
if (ModelState.IsValid)
{
MailMessage message = new MailMessage();
message.From = new MailAddress("address#gmail.com");
message.To.Add(new MailAddress("address#hotmail.com"));
message.Subject = "";
message.Body = "";
SmtpClient client = new SmtpClient();
client.Send(message);
return View("Index");
}
else
{
return View();
}
}
}
Model
namespace msifla.Models
{
public class AddressModel
{
public AddressModel()
{
AvailableUSStates = new List<SelectListItem>();
AvailableCounties = new List<SelectListItem>();
}
[Display(Name = "USState")]
public int USStateID { get; set; }
public List<SelectListItem> AvailableUSStates { get; set; }
[Display(Name = "County")]
public int CountyID { get; set; }
public List<SelectListItem> AvailableCounties { get; set; }
}
}
View
#model msifla.Models.AddressModel
#{
ViewBag.Title = "Index";
}
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.min.js"></script>
<script type="text/javascript">
$(function () {
$("#USStateID").change(function () {
var selectedItem = $(this).val();
var ddlCounties = $("#CountyID");
var countiesProgress = $("#counties-loading-progress");
$('.selItem').remove();
var selectedItem2 = $('<p class="selItem">' + selectedItem + '</p>');
$('.usState').append(selectedItem2);
//$('.usState').append($('<p>This works here</p>'));
countiesProgress.show();
$.ajax({
cache: false,
type: "GET",
url: "#(Url.RouteUrl("GetCountiesByUSStateID"))",
data: { "USStateID": selectedItem },
success: function (data) {
ddlCounties.html('');
$.each(data, function (id, option) {
ddlCounties.append($('<option> </option>').val(option.id).html(option.name));
});
alert(option.name);
countiesProgress.hide();
},
error: function (xhr, ajaxOptions, thrownError) {
alert('Failed to retrieve states.');
countiesProgress.hide();
}
});
});
});
</script>
#using (Html.BeginForm())
{
<div>
#Html.LabelFor(model => model.USStateID)
#Html.DropDownListFor(model => model.USStateID, Model.AvailableUSStates)
</div>
<br />
<div>
#Html.LabelFor(model => model.CountyID)
#Html.DropDownListFor(model => model.CountyID, Model.AvailableCounties)
<span id="counties-loading-progress" style="display: none;">Please wait..</span>
</div>
<div class="usState"></div>
<input name="submit" type="submit" id="submit" value="Save"/>
<label id="stateLabel"></label>
}
Let me know if you need to see the repository.
Thank you in advance for your help.
Edit
I know this is old, but I found a solution and wanted to post it here. It has been a while since i fixed my issue so I don't remember where I found the solution, but here it is:
Controller
public ActionResult Index()
{
AddressModel model = new AddressModel();
model.AvailableUSStates.Add(new SelectListItem { Text = "-Please select-", Value = "Selects items" });
model.AvailableLibraries.Add(new SelectListItem { Text = "-Please select-", Value = "Selects items" });
var usstates = _repository.GetAllUSStates();
foreach (var usstate in usstates)
{
model.AvailableUSStates.Add(new SelectListItem()
{
Text = usstate.USStateName,
Value = usstate.USStateID.ToString()
});
}
return View(model);
}
[AcceptVerbs(HttpVerbs.Get)]
public ActionResult GetLibrariesByUSStateID(string USStateID)
{
if (string.IsNullOrEmpty(USStateID))
{
throw new ArgumentNullException("USStateID");
}
int id = 0;
bool isValid = Int32.TryParse(USStateID, out id);
var counties = _repository.GetAllLibrariesByUSStateID(id);
var result = (from s in counties
select new
{
id = s.LibraryID,
name = s.LibraryName
}).ToList();
return Json(result, JsonRequestBehavior.AllowGet);
}
[AcceptVerbs(HttpVerbs.Post)]
//[ValidateAntiForgeryToken]
public ActionResult Index(AddressModel model)
{
var errors = ModelState.Values.SelectMany(v => v.Errors);
if (ModelState.IsValid)
{
ConfirmModel model2 = new ConfirmModel();
model2.USStateName = SelectedUSState(model.USStateID.ToString());
model2.CountyName = SelectedCounty(model.LibraryID.ToString(), model.USStateID.ToString());
model2.CountyID = model.LibraryID;
model2.clientID = model.clientId.ToString();
return View("Confirmation", model2);
}
return View(model);
}
public ActionResult Confirmation(AddressModel model2)
{
ConfirmModel model = new ConfirmModel();
model.USStateName = SelectedUSState(model2.USStateID.ToString());
model.CountyName = SelectedCounty(model2.LibraryID.ToString(), model2.USStateID.ToString());
var USStateName = model.USStateName;
return View(model);
}
//[AcceptVerbs(HttpVerbs.Get)]
//public ActionResult Confirmation(ConfirmModel model)
//{
// string USStateName = model.USStateName;
// return View();
//}
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult submitConfirmation(ConfirmModel model)
{
if (ModelState.IsValid)
{
string usStateName = model.USStateName;
string countyName = model.CountyName;
DateTime dateTime = DateTime.Now;
string ipAddress = Request.UserHostAddress;
string ipAddress2 = Request.ServerVariables["Remote_Addr"];
string userAgent = Request.UserAgent;
MailMessage message = new MailMessage();
message.From = new MailAddress("someone#domain.com");
message.To.Add(new MailAddress("someoneElse#domain.com"));
message.Subject = "Subject";
// You need to use Index because that is the name declared above
message.Body = "<!DOCTYPE html><head></head><body>" +
"<pre>State:\t\t" + usStateName + "</pre>" +
"<pre>County:\t\t" + countyName + "</pre>" +
"<pre>Remote Name:\t" + ipAddress + "</pre>" +
"<pre>Remote User:\t" + userAgent + "</pre>" +
"<pre>Date:\t" + dateTime.ToLongDateString() + "</pre>" +
"<pre>Time:\t" + dateTime.ToLongTimeString() + "</pre>" +
"\n"
"</body>";
message.IsBodyHtml = true;
SmtpClient client = new SmtpClient();
client.Send(message);
return RedirectToAction("Index");
}
return View(model);
}
[HttpPost]
public ActionResult resetConfirmation()
{
return RedirectToAction("Index");
}
public string SelectedUSState(string USStateID)
{
ViewBag.YouSelected = USStateID.ToString();
AddressModel model = new AddressModel();
int id = 0;
int usStateIDInt = int.Parse(USStateID);
bool isValid = Int32.TryParse(USStateID, out id);
var usstates = _repository.GetAllUSStates();
var state = from s in _repository.GetAllUSStates()
where s.USStateID.ToString() == USStateID
select s.USStateName;
var currUSState = state.SingleOrDefault();
//var currUSStatename = usstates.te
//model.USStateName = currUSState;
ViewBag.currUSState = currUSState;
return currUSState;
}
public string SelectedCounty(string CountyID, string USStateID)
{
AddressModel model = new AddressModel();
int id = 0;
int countyIDInt = int.Parse(CountyID);
bool isValid = Int32.TryParse(CountyID, out id);
int usStateIDInt = int.Parse(USStateID);
var counties = _repository.GetAllLibrariesByUSStateID(usStateIDInt);
var county = from s in counties
where s.LibraryID.ToString() == CountyID
select s.LibraryName;
var currCounty = county.SingleOrDefault();
ViewBag.currCounty = currCounty;
return currCounty;
}
Model
public class AddressModel
{
public AddressModel()
{
AvailableUSStates = new List<SelectListItem>();
AvailableLibraries = new List<SelectListItem>();
}
[Display(Name = "USState")]
[Required(ErrorMessage = ("Please choose a State"))]
public int USStateID { get; set; }
//public string USStateName { get; set; }
public List<SelectListItem> AvailableUSStates { get; set; }
[Display(Name = "Library")]
[Required(ErrorMessage = ("Please chose a Library for the selected State"))]
public int LibraryID { get; set; }
public List<SelectListItem> AvailableLibraries { get; set; }
}
public class ConfirmModel
{
[Display(Name = "State Name")]
public string USStateName { get; set; }
[Display(Name = "County Name")]
public string CountyName { get; set; }
}
View
#model msifla2.Models.MSIProModel
#{
ViewBag.Title = "HCOrder";
}
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.min.js"></script>
#*<script src="~/Scripts/angular.min.js"></script>*#
#*<script src="~/Scripts/cascade.js"></script>*#
<script type="text/javascript">
$(function () {
$("#USStateDDL").change(function () {
var selectedItem = $(this).val();
var ddlLibraries = $("#LibraryID");
var librariesProgress = $("#libraries-loading-progress");
librariesProgress.show();
$.ajax({
cache: false,
type: "GET",
url: "#(Url.RouteUrl("GetLibrariesByUSStateID"))",
data: { "USStateID": selectedItem },
success: function (data) {
ddlLibraries.html('');
$.each(data, function (id, option) {
ddlLibraries.append($('<option>Select a Library</option>').val(option.id).html(option.name));
});
librariesProgress.hide();
},
error: function (xhr, ajaxOptions, thrownError) {
alert('Failed to retrieve libraries.');
librariesProgress.hide();
}
});
});
});
</script>
#*<script>
$(function () {
$('#USStateDDL').change(function () {
$.ajax({
url: this.href,
type: 'GET',
cache: false,
data: { selectedValue: $('#USStateDDL').val() },
success: function (result) {
alert('#USStateDDL').val();
}
})
var selected = $(this).val();
alert(selected + " 1 selected")
$('#USStateLabel').load(input)
});
});
</script>*#
<div class="jumbotron">
</div>
<div class="container article">
<div data-ng-app="myModule" class="col-md-9 article_main container-fluid">
<h2>Header</h2>
#using (Html.BeginForm("Address", "Home", FormMethod.Post))
{
<div class="edit-label">
#Html.LabelFor(model => model.USStateID, new { id = "USStateLabel", #class = "col-xs-3" })
</div>
<div class="edit-field, col-xs-9">
#Html.DropDownListFor(model => model.USStateID, Model.AvailableUSStates, new { #class = "form-control dropdowns", id = "USStateDDL" })
</div>
#Html.LabelFor(model => model.LibraryID, new { #class = "col-xs-3" })
<div class=" col-xs-9">
#Html.DropDownListFor(model => model.LibraryID, Model.AvailableLibraries, new { #class = "form-control" })
</div>
<div class="col-xs-9 col-xs-offset-3" style="padding-top:5px;">
<input type="submit" id="submit" value="Send" class="btn-success btn" />
</div>
}
</div>
</div>
</div>
</div>
Confirm View
#model msifla2.Models.ConfirmModel
#{
ViewBag.Title = "Confirmation";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Confirmation</h2>
#using (Html.BeginForm("submitConfirmation", "Home", FormMethod.Post))
{
<div data-ng-app="myModule" class="col-md-9 article_main">
<div>
<h4>Please check your order and select <b>Confirm</b> to submit</h4>
</div>
<div class="row">
#Html.LabelFor(model => model.USStateName, new { #class = "col-xs-3" })
#Html.DisplayTextFor(model => model.USStateName)
#Html.HiddenFor(model => model.USStateName)
</div>
<div class="row">
#Html.LabelFor(model => model.CountyName, new { #class = "col-xs-3" })
#Html.DisplayTextFor(model => model.CountyName)
#Html.HiddenFor(model => model.CountyName)
</div>
<input type="submit" formaction="/home/submitConfirmation" value="Confirm" />
<input type="submit" formaction="/Home/resetConfirmation" value="Reset" />
</div>
}
I think I included everything. Let me know if you see something missing, but it's working for me.
If I understood your question correctly:
change
ddlCounties.append($('<option> </option>').val(option.id).html(option.name));
to
ddlCounties.append($('<option> </option>').val(option.name).html(option.name));
your model should also have the Name.
I know this is old, but I found a solution and wanted to post it here. It has been a while since i fixed my issue so I don't remember where I found the solution, but here it is:
Controller
public ActionResult Index()
{
AddressModel model = new AddressModel();
model.AvailableUSStates.Add(new SelectListItem { Text = "-Please select-", Value = "Selects items" });
model.AvailableLibraries.Add(new SelectListItem { Text = "-Please select-", Value = "Selects items" });
var usstates = _repository.GetAllUSStates();
foreach (var usstate in usstates)
{
model.AvailableUSStates.Add(new SelectListItem()
{
Text = usstate.USStateName,
Value = usstate.USStateID.ToString()
});
}
return View(model);
}
[AcceptVerbs(HttpVerbs.Get)]
public ActionResult GetLibrariesByUSStateID(string USStateID)
{
if (string.IsNullOrEmpty(USStateID))
{
throw new ArgumentNullException("USStateID");
}
int id = 0;
bool isValid = Int32.TryParse(USStateID, out id);
var counties = _repository.GetAllLibrariesByUSStateID(id);
var result = (from s in counties
select new
{
id = s.LibraryID,
name = s.LibraryName
}).ToList();
return Json(result, JsonRequestBehavior.AllowGet);
}
[AcceptVerbs(HttpVerbs.Post)]
//[ValidateAntiForgeryToken]
public ActionResult Index(AddressModel model)
{
var errors = ModelState.Values.SelectMany(v => v.Errors);
if (ModelState.IsValid)
{
ConfirmModel model2 = new ConfirmModel();
model2.USStateName = SelectedUSState(model.USStateID.ToString());
model2.CountyName = SelectedCounty(model.LibraryID.ToString(), model.USStateID.ToString());
model2.CountyID = model.LibraryID;
model2.clientID = model.clientId.ToString();
return View("Confirmation", model2);
}
return View(model);
}
public ActionResult Confirmation(AddressModel model2)
{
ConfirmModel model = new ConfirmModel();
model.USStateName = SelectedUSState(model2.USStateID.ToString());
model.CountyName = SelectedCounty(model2.LibraryID.ToString(), model2.USStateID.ToString());
var USStateName = model.USStateName;
return View(model);
}
//[AcceptVerbs(HttpVerbs.Get)]
//public ActionResult Confirmation(ConfirmModel model)
//{
// string USStateName = model.USStateName;
// return View();
//}
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult submitConfirmation(ConfirmModel model)
{
if (ModelState.IsValid)
{
string usStateName = model.USStateName;
string countyName = model.CountyName;
DateTime dateTime = DateTime.Now;
string ipAddress = Request.UserHostAddress;
string ipAddress2 = Request.ServerVariables["Remote_Addr"];
string userAgent = Request.UserAgent;
MailMessage message = new MailMessage();
message.From = new MailAddress("someone#domain.com");
message.To.Add(new MailAddress("someoneElse#domain.com"));
message.Subject = "Subject";
// You need to use Index because that is the name declared above
message.Body = "<!DOCTYPE html><head></head><body>" +
"<pre>State:\t\t" + usStateName + "</pre>" +
"<pre>County:\t\t" + countyName + "</pre>" +
"<pre>Remote Name:\t" + ipAddress + "</pre>" +
"<pre>Remote User:\t" + userAgent + "</pre>" +
"<pre>Date:\t" + dateTime.ToLongDateString() + "</pre>" +
"<pre>Time:\t" + dateTime.ToLongTimeString() + "</pre>" +
"\n"
"</body>";
message.IsBodyHtml = true;
SmtpClient client = new SmtpClient();
client.Send(message);
return RedirectToAction("Index");
}
return View(model);
}
[HttpPost]
public ActionResult resetConfirmation()
{
return RedirectToAction("Index");
}
public string SelectedUSState(string USStateID)
{
ViewBag.YouSelected = USStateID.ToString();
AddressModel model = new AddressModel();
int id = 0;
int usStateIDInt = int.Parse(USStateID);
bool isValid = Int32.TryParse(USStateID, out id);
var usstates = _repository.GetAllUSStates();
var state = from s in _repository.GetAllUSStates()
where s.USStateID.ToString() == USStateID
select s.USStateName;
var currUSState = state.SingleOrDefault();
//var currUSStatename = usstates.te
//model.USStateName = currUSState;
ViewBag.currUSState = currUSState;
return currUSState;
}
public string SelectedCounty(string CountyID, string USStateID)
{
AddressModel model = new AddressModel();
int id = 0;
int countyIDInt = int.Parse(CountyID);
bool isValid = Int32.TryParse(CountyID, out id);
int usStateIDInt = int.Parse(USStateID);
var counties = _repository.GetAllLibrariesByUSStateID(usStateIDInt);
var county = from s in counties
where s.LibraryID.ToString() == CountyID
select s.LibraryName;
var currCounty = county.SingleOrDefault();
ViewBag.currCounty = currCounty;
return currCounty;
}
Model
public class AddressModel
{
public AddressModel()
{
AvailableUSStates = new List<SelectListItem>();
AvailableLibraries = new List<SelectListItem>();
}
[Display(Name = "USState")]
[Required(ErrorMessage = ("Please choose a State"))]
public int USStateID { get; set; }
//public string USStateName { get; set; }
public List<SelectListItem> AvailableUSStates { get; set; }
[Display(Name = "Library")]
[Required(ErrorMessage = ("Please chose a Library for the selected State"))]
public int LibraryID { get; set; }
public List<SelectListItem> AvailableLibraries { get; set; }
}
public class ConfirmModel
{
[Display(Name = "State Name")]
public string USStateName { get; set; }
[Display(Name = "County Name")]
public string CountyName { get; set; }
}
View
#model msifla2.Models.MSIProModel
#{
ViewBag.Title = "HCOrder";
}
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.min.js"></script>
#*<script src="~/Scripts/angular.min.js"></script>*#
#*<script src="~/Scripts/cascade.js"></script>*#
<script type="text/javascript">
$(function () {
$("#USStateDDL").change(function () {
var selectedItem = $(this).val();
var ddlLibraries = $("#LibraryID");
var librariesProgress = $("#libraries-loading-progress");
librariesProgress.show();
$.ajax({
cache: false,
type: "GET",
url: "#(Url.RouteUrl("GetLibrariesByUSStateID"))",
data: { "USStateID": selectedItem },
success: function (data) {
ddlLibraries.html('');
$.each(data, function (id, option) {
ddlLibraries.append($('<option>Select a Library</option>').val(option.id).html(option.name));
});
librariesProgress.hide();
},
error: function (xhr, ajaxOptions, thrownError) {
alert('Failed to retrieve libraries.');
librariesProgress.hide();
}
});
});
});
</script>
#*<script>
$(function () {
$('#USStateDDL').change(function () {
$.ajax({
url: this.href,
type: 'GET',
cache: false,
data: { selectedValue: $('#USStateDDL').val() },
success: function (result) {
alert('#USStateDDL').val();
}
})
var selected = $(this).val();
alert(selected + " 1 selected")
$('#USStateLabel').load(input)
});
});
</script>*#
<div class="jumbotron">
</div>
<div class="container article">
<div data-ng-app="myModule" class="col-md-9 article_main container-fluid">
<h2>Header</h2>
#using (Html.BeginForm("Address", "Home", FormMethod.Post))
{
<div class="edit-label">
#Html.LabelFor(model => model.USStateID, new { id = "USStateLabel", #class = "col-xs-3" })
</div>
<div class="edit-field, col-xs-9">
#Html.DropDownListFor(model => model.USStateID, Model.AvailableUSStates, new { #class = "form-control dropdowns", id = "USStateDDL" })
</div>
#Html.LabelFor(model => model.LibraryID, new { #class = "col-xs-3" })
<div class=" col-xs-9">
#Html.DropDownListFor(model => model.LibraryID, Model.AvailableLibraries, new { #class = "form-control" })
</div>
<div class="col-xs-9 col-xs-offset-3" style="padding-top:5px;">
<input type="submit" id="submit" value="Send" class="btn-success btn" />
</div>
}
</div>
</div>
</div>
</div>
Confirm View
#model msifla2.Models.ConfirmModel
#{
ViewBag.Title = "Confirmation";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Confirmation</h2>
#using (Html.BeginForm("submitConfirmation", "Home", FormMethod.Post))
{
<div data-ng-app="myModule" class="col-md-9 article_main">
<div>
<h4>Please check your order and select <b>Confirm</b> to submit</h4>
</div>
<div class="row">
#Html.LabelFor(model => model.USStateName, new { #class = "col-xs-3" })
#Html.DisplayTextFor(model => model.USStateName)
#Html.HiddenFor(model => model.USStateName)
</div>
<div class="row">
#Html.LabelFor(model => model.CountyName, new { #class = "col-xs-3" })
#Html.DisplayTextFor(model => model.CountyName)
#Html.HiddenFor(model => model.CountyName)
</div>
<input type="submit" formaction="/home/submitConfirmation" value="Confirm" />
<input type="submit" formaction="/Home/resetConfirmation" value="Reset" />
</div>
}
I think I included everything. Let me know if you see something missing, but it's working for me.