I'm implementing asp.net core project and I have a selectList that shows regions and after choosing a region from it, I want to fetch related data to a second dropdown that shows zones. Here is my code till now:
My edited code:
public class OperatorViewModel {
public IEnumerable<BuyWasteRequestViewModel> BuyWasteRequestVM { get; set; }
[Required] public string SelectedRegionID { get; set; }
[Required]
public string SelectedZoneID { get; set; }
public string SelectedRegionText { get; set; }
public string SelectedZoneText { get; set; }
}
And Here my view:
#model MyProject.ViewModels.OperatorViewModel
<form method="post">
#Html.DropDownListFor(m => m.SelectedRegionID, (IEnumerable<SelectListItem>)ViewBag.RegionId, "select", new { #style = "position: absolute; width: 42%; padding: 2%; border: 1px solid #ced4da; border-radius: 3px; right: 4.5rem; height: 2.35rem;" })
#Html.HiddenFor(m => m.SelectedRegionText)
<select id="SelectedZoneID" name="#Html.NameFor(c=>c.SelectedZoneID)" class="form-control statesSelect" asp-items="#(new SelectList(#ViewBag.ZoneID,"Id", "Name"))">
<option value='0'>select</option>
</select>
#Html.HiddenFor(m => m.SelectedZoneText)
</form>
<script>
jQuery(document).ready(function ($) {
$("#SelectedRegionID")
.change(function () {
var id = $(this).val();
$("#SelectedRegionText").attr("value", $("#SelectedRegionID option:selected").text());
$.getJSON('#Url.Action("GetZones", "Operator")/' + id, function (data) {
//delete the options of $("#SelectedZoneID") and add new options
$("#SelectedZoneID").empty();
$("#SelectedZoneID").append('<option value="0">select</option>');
$.each(data, function (value, text) {
$("#SelectedZoneID").append('<option value="' + text.value + '">' + text.text + '</option>');
});
});
});
$("#SelectedZoneID").change(function () {
$("#SelectedZoneText").attr("value", $("#SelectedZoneID option:selected").text());
});
$("#SelectedRegionID")
.change(function() {
$('#SelectedRegionText').val($(this).find("option:selected").text());
});
In my controller:
public class OperatorController : Controller
{
private readonly WasteAPIContext _context;
public OperatorController(WasteAPIContext context)
{
_context = context;
}
[HttpPost]
public IActionResult Index(OperatorViewModel buywastervm)
{
return BuildIndexModel(buywastervm.SelectedRegionID, buywastervm.SelectedRegionText, buywastervm.SelectedZoneID, buywastervm.SelectedZoneText);
}
public IActionResult BuildIndexModel(string selectedRegionID, string selectedRegionText,string selectedZoneID, string selectedZoneText){
ViewData["RegionId"] = new SelectList(_context.Region, "Id", "Name", "select");
ViewData["ZoneId"] = new SelectList(_context.Zone.Where(c => c.RegionId == selectedZoneID), "Id", "Name", "select");
OperatorVM.BuyWasteRequestVM = bwrvm;
OperatorVM.SelectedRegionID = selectedRegionID;
OperatorVM.SelectedRegionText = selectedRegionText;
OperatorVM.SelectedZoneID = selectedZoneID;
OperatorVM.SelectedZoneText = selectedZoneText;
return View(OperatorVM);
}
public JsonResult GetZones(string ID)
{
List<SelectListItem> ZoneList = new List<SelectListItem>();
var zones = _context.Zone.Where(c => c.RegionId == ID).Select(c => new
{
Value = c.Id,
Text = c.Name
}).ToList();
foreach (var item in zones)
{
SelectListItem slist = new SelectListItem();
slist.Value = item.Value; /*0 + mvalue*/
slist.Text = item.Text;
ZoneList.Add(slist);
}
ViewData["ZoneId"] = new SelectList(_context.Zone.Where(c => c.RegionId == ID), "Id", "Name", "select");
return Json(ZoneList);
}
Now my problem is, I want after choosing my considering region from region selectlist and accordingly choosing an item from zone selectlist and then submitting the form, I have the ability to see all populated related zones to selected region displayed before submitting the form in zone selectlist. Right now, after submitting the form, I'm just able to see item in zone selectlist. Moreover, I need after submitting the form, the user can see the selected item in zone list as the selected option. Now I can see the selected region in Region selectlist after submitting the form which I set its data in my model after submitting the form. I kindly appreciate of any help.
Here is a working demo:
View(TestOperatorViewModel.cshtml):
<form method="post" style="height: 4rem;">
<table cellspacing="5" cellpadding="5" border="0">
<tbody>
<tr>
<td>
<label>
region:
#Html.DropDownListFor(m => m.SelectedRegionID, (IEnumerable<SelectListItem>)ViewBag.RegionId, "select")
#Html.HiddenFor(m => m.SelectedRegionText)
</label>
</td>
<td>
<label>
Zone:
#* I change the dropdownlist *#
<select id="SelectedZoneID" name="SelectedZoneID">
<option value='0'>select</option>
</select>
#Html.HiddenFor(m => m.SelectedZoneText)
</label>
</td>
</tr>
</tbody>
</table>
<button>submit</button>
</form>
#section scripts{
<script>
$("#SelectedRegionID")
.change(function () {
var id = $(this).val();
$("#SelectedRegionText").attr("value", $("#SelectedRegionID option:selected").text());
$.getJSON('#Url.Action("GetZones", "Test")/' + id, function (data) {
//delete the options of $("#SelectedZoneID") and add new options
$("#SelectedZoneID").empty();
$("#SelectedZoneID").append('<option value="0">select</option>');
$.each(data, function (value, text) {
$("#SelectedZoneID").append('<option value="' + value + '">' + text.text + '</option>');
});
});
});
$("#SelectedZoneID").change(function () {
$("#SelectedZoneText").attr("value", $("#SelectedZoneID option:selected").text());
})
</script>
}
Controller(I use fake data to test,ControllerName is TestController):
[HttpGet]
public IActionResult TestOperatorViewModel()
{
List<SelectListItem> RegionId = new List<SelectListItem>();
RegionId.Add(new SelectListItem { Value = "r1", Text = "id1" });
RegionId.Add(new SelectListItem { Value = "r2", Text = "id2" });
RegionId.Add(new SelectListItem { Value = "r3", Text = "id3" });
ViewBag.RegionId = RegionId;
return View();
}
[HttpPost]
public IActionResult TestOperatorViewModel(OperatorViewModel operatorViewModel)
{
return Ok();
}
public JsonResult GetZones(string ID)
{
List<SelectListItem> ZoneList = new List<SelectListItem>();
ZoneList.Add(new SelectListItem { Value = "1", Text = "one"+ID });
ZoneList.Add(new SelectListItem { Value = "2", Text = "two"+ID });
ZoneList.Add(new SelectListItem { Value = "3", Text = "three"+ID });
return Json(ZoneList);
}
result:
Related
I am using MVC Razor View.
At the top of my form I have the following:
#using (Html.BeginForm())
it appears that none of my checkboxes or radiobuttons, or dropdown are working, they are all returning a value of null
checkbox : the model.Domestic is a boolean, could this be an issue? returns null
#Html.CheckBoxFor(model => model.Domestic.Value, new { value = Model.Domestic.Value ? "checked" : "" }) <span class="display-checkbox">Domestic</span>
radio button returns null
#Html.RadioButtonFor(model => model.Subscription_Renewal, false, new { id = "SR_ChkNo", value = "checked", onclick = "checkButtonDt();" }) <span class="largeText_light">N/A</span>
dropdown:
backend code:
// Create the Categories Select List
var categoryList = new List<SelectListItem>();
foreach (Category c in returned.Categories)
{
categoryList.Add(new SelectListItem
{
Value = c.Category_ID.ToString(),
Text = c.Description,
Selected = (c.Category_ID == returned.Category_ID ? true : false)
});
}
returned.CategoryList = categoryList;
then in the View: I tried to select a entry from the selected list, and it returns 0
#Html.DropDownList("category", Model.CategoryList, new { #class = "input-box" })
Here is a demo to bind data with checkbox,radiobutton and dropdownlist when posting form:
Model:
public class BindModel
{
public List<SelectListItem> CategoryList { get; set; }
public string Subscription_Renewal { get; set; }
public bool Domestic { get; set; }
public string category { get; set; }
}
View:
#using (Html.BeginForm())
{
#Html.CheckBoxFor(model => model.Domestic)<span class="display-checkbox">Domestic</span>
<input type="radio" name="Subscription_Renewal" value="Male" /><span class="largeText_light">Male</span>
<input type="radio" name="Subscription_Renewal" value="Female" /><span class="largeText_light">Female</span>
<input type="radio" name="Subscription_Renewal" value="Unspecified" /><span class="largeText_light">Unspecified</span>
#Html.DropDownList("category", Model.CategoryList, new { #class = "input-box" })
<input type="submit" value="submit" />
}
Controller:
public IActionResult TestBind(BindModel bindModel) {
BindModel returned = new BindModel();
var categoryList = new List<SelectListItem> {
new SelectListItem { Value="1", Text="Category1",Selected=true},
new SelectListItem { Value = "2", Text = "Category2", Selected = false },
new SelectListItem { Value = "3", Text = "Category3", Selected = false } };
returned.CategoryList = categoryList;
return View(returned);
}
result:
I have dropdownlist, which I have filled from database. Now I need to get the selected value in Controller do some manipulation. But not getting the idea. Code which I have tried.
Model
public class MobileViewModel
{
public List<tbInsertMobile> MobileList;
public SelectList Vendor { get; set; }
}
Controller
public ActionResult ShowAllMobileDetails()
{
MobileViewModel MV = new MobileViewModel();
MV.MobileList = db.Usp_InsertUpdateDelete(null, "", "", null, "", 4, MergeOption.AppendOnly).ToList();
MV.Vendor = new SelectList(db.Usp_VendorList(), "VendorId", "VendorName");
return View(MV);
}
[HttpPost]
public ActionResult ShowAllMobileDetails(MobileViewModel MV)
{
string strDDLValue = ""; // Here i need the dropdownlist value
return View(MV);
}
View
<table>
<tr>
<td>Mobile Manufacured</td>
<td>#Html.DropDownList("ddlVendor", Model.Vendor, "Select Manufacurer") </td>
</tr>
<tr>
<td>
</td>
<td>
<input id="Submit1" type="submit" value="search" />
</td>
</tr>
</table>
1st Approach (via Request or FormCollection):
You can read it from Request using Request.Form , your dropdown name is ddlVendor so pass ddlVendor key in the formCollection to get its value that is posted by form:
string strDDLValue = Request.Form["ddlVendor"].ToString();
or Use FormCollection:
[HttpPost]
public ActionResult ShowAllMobileDetails(MobileViewModel MV,FormCollection form)
{
string strDDLValue = form["ddlVendor"].ToString();
return View(MV);
}
2nd Approach (Via Model):
If you want with Model binding then add a property in Model:
public class MobileViewModel
{
public List<tbInsertMobile> MobileList;
public SelectList Vendor { get; set; }
public string SelectedVendor {get;set;}
}
and in View:
#Html.DropDownListFor(m=>m.SelectedVendor , Model.Vendor, "Select Manufacurer")
and in Action:
[HttpPost]
public ActionResult ShowAllMobileDetails(MobileViewModel MV)
{
string SelectedValue = MV.SelectedVendor;
return View(MV);
}
UPDATE:
If you want to post the text of selected item as well, you have to add a hidden field and on drop down selection change set selected item text in the hidden field:
public class MobileViewModel
{
public List<tbInsertMobile> MobileList;
public SelectList Vendor { get; set; }
public string SelectVendor {get;set;}
public string SelectedvendorText { get; set; }
}
use jquery to set hidden field:
<script type="text/javascript">
$(function(){
$("#SelectedVendor").on("change", function {
$("#SelectedvendorText").val($(this).text());
});
});
</script>
#Html.DropDownListFor(m=>m.SelectedVendor , Model.Vendor, "Select Manufacurer")
#Html.HiddenFor(m=>m.SelectedvendorText)
Model
Very basic model with Gender field. GetGenderSelectItems() returns select items needed to populate DropDownList.
public enum Gender
{
Male, Female
}
public class MyModel
{
public Gender Gender { get; set; }
public static IEnumerable<SelectListItem> GetGenderSelectItems()
{
yield return new SelectListItem { Text = "Male", Value = "Male" };
yield return new SelectListItem { Text = "Female", Value = "Female" };
}
}
View
Please make sure you wrapped your #Html.DropDownListFor in a form tag.
#model MyModel
#using (Html.BeginForm("MyController", "MyAction", FormMethod.Post)
{
#Html.DropDownListFor(m => m.Gender, MyModel.GetGenderSelectItems())
<input type="submit" value="Send" />
}
Controller
Your .cshtml Razor view name should be the same as controller action name and folder name should match controller name e.g Views\MyController\MyAction.cshtml.
public class MyController : Controller
{
public ActionResult MyAction()
{
// shows your form when you load the page
return View();
}
[HttpPost]
public ActionResult MyAction(MyModel model)
{
// the value is received in the controller.
var selectedGender = model.Gender;
return View(model);
}
}
Going further
Now let's make it strongly-typed and enum independent:
var genderSelectItems = Enum.GetValues(typeof(Gender))
.Cast<string>()
.Select(genderString => new SelectListItem
{
Text = genderString,
Value = genderString,
}).AsEnumerable();
MVC 5/6/Razor Pages
I think the best way is with strongly typed model, because Viewbags are being aboused too much already :)
MVC 5 example
Your Get Action
public async Task<ActionResult> Register()
{
var model = new RegistrationViewModel
{
Roles = GetRoles()
};
return View(model);
}
Your View Model
public class RegistrationViewModel
{
public string Name { get; set; }
public int? RoleId { get; set; }
public List<SelectListItem> Roles { get; set; }
}
Your View
<div class="form-group">
#Html.LabelFor(model => model.RoleId, htmlAttributes: new { #class = "col-form-label" })
<div class="col-form-txt">
#Html.DropDownListFor(model => model.RoleId, Model.Roles, "--Select Role--", new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.RoleId, "", new { #class = "text-danger" })
</div>
</div>
Your Post Action
[HttpPost, ValidateAntiForgeryToken]
public async Task<ActionResult> Register(RegistrationViewModel model)
{
if (ModelState.IsValid)
{
var _roleId = model.RoleId,
MVC 6 It'll be a little different
Get Action
public async Task<ActionResult> Register()
{
var _roles = new List<SelectListItem>();
_roles.Add(new SelectListItem
{
Text = "Select",
Value = ""
});
foreach (var role in GetRoles())
{
_roles.Add(new SelectListItem
{
Text = z.Name,
Value = z.Id
});
}
var model = new RegistrationViewModel
{
Roles = _roles
};
return View(model);
}
Your View Model will be same as MVC 5
Your View will be like
<select asp-for="RoleId" asp-items="Model.Roles"></select>
Post will also be same
Razor Pages
Your Page Model
[BindProperty]
public int User User { get; set; } = 1;
public List<SelectListItem> Roles { get; set; }
public void OnGet()
{
Roles = new List<SelectListItem> {
new SelectListItem { Value = "1", Text = "X" },
new SelectListItem { Value = "2", Text = "Y" },
new SelectListItem { Value = "3", Text = "Z" },
};
}
<select asp-for="User" asp-items="Model.Roles">
<option value="">Select Role</option>
</select>
I hope it may help someone :)
If you want to use #Html.DropDownList , follow.
Controller:
var categoryList = context.Categories.Select(c => c.CategoryName).ToList();
ViewBag.CategoryList = categoryList;
View:
#Html.DropDownList("Category", new SelectList(ViewBag.CategoryList), "Choose Category", new { #class = "form-control" })
$("#Category").on("change", function () {
var q = $("#Category").val();
console.log("val = " + q);
});
If you're looking for something lightweight, I'd append a parameter to your action.
[HttpPost]
public ActionResult ShowAllMobileDetails(MobileViewModel MV, string ddlVendor)
{
string strDDLValue = ddlVendor; // Of course, this becomes silly.
return View(MV);
}
What's happening in your code now, is you're passing the first string argument of "ddlVendor" to Html.DropDownList, and that's telling the MVC framework to create a <select> element with a name of "ddlVendor." When the user submits the form client-side, then, it will contain a value to that key.
When MVC tries to parse that request into MV, it's going to look for MobileList and Vendor and not find either, so it's not going to be populated. By adding this parameter, or using FormCollection as another answer has suggested, you're asking MVC to specifically look for a form element with that name, so it should then populate the parameter value with the posted value.
Use SelectList to bind #HtmlDropdownListFor and specify selectedValue parameter in it.
http://msdn.microsoft.com/en-us/library/dd492553(v=vs.108).aspx
Example : you can do like this for getting venderid
#Html.DropDownListFor(m => m.VendorId,Model.Vendor)
public class MobileViewModel
{
public List<tbInsertMobile> MobileList;
public SelectList Vendor { get; set; }
public int VenderID{get;set;}
}
[HttpPost]
public ActionResult Action(MobileViewModel model)
{
var Id = model.VenderID;
I was having the same issue in asp.NET razor C#
I had a ComboBox filled with titles from an EventMessage, and I wanted to show the Content of this message with its selected value to show it in a label or TextField or any other Control...
My ComboBox was filled like this:
#Html.DropDownList("EventBerichten", new SelectList(ViewBag.EventBerichten, "EventBerichtenID", "Titel"), new { #class = "form-control", onchange = "$(this.form).submit();" })
In my EventController I had a function to go to the page, in which I wanted to show my ComboBox (which is of a different model type, so I had to use a partial view)?
The function to get from index to page in which to load the partial view:
public ActionResult EventDetail(int id)
{
Event eventOrg = db.Event.Include(s => s.Files).SingleOrDefault(s => s.EventID == id);
// EventOrg eventOrg = db.EventOrgs.Find(id);
if (eventOrg == null)
{
return HttpNotFound();
}
ViewBag.EventBerichten = GetEventBerichtenLijst(id);
ViewBag.eventOrg = eventOrg;
return View(eventOrg);
}
The function for the partial view is here:
public PartialViewResult InhoudByIdPartial(int id)
{
return PartialView(
db.EventBericht.Where(r => r.EventID == id).ToList());
}
The function to fill EventBerichten:
public List<EventBerichten> GetEventBerichtenLijst(int id)
{
var eventLijst = db.EventBericht.ToList();
var berLijst = new List<EventBerichten>();
foreach (var ber in eventLijst)
{
if (ber.EventID == id )
{
berLijst.Add(ber);
}
}
return berLijst;
}
The partialView Model looks like this:
#model IEnumerable<STUVF_back_end.Models.EventBerichten>
<table>
<tr>
<th>
EventID
</th>
<th>
Titel
</th>
<th>
Inhoud
</th>
<th>
BerichtDatum
</th>
<th>
BerichtTijd
</th>
</tr>
#foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.EventID)
</td>
<td>
#Html.DisplayFor(modelItem => item.Titel)
</td>
<td>
#Html.DisplayFor(modelItem => item.Inhoud)
</td>
<td>
#Html.DisplayFor(modelItem => item.BerichtDatum)
</td>
<td>
#Html.DisplayFor(modelItem => item.BerichtTijd)
</td>
</tr>
}
</table>
VIEUW: This is the script used to get my output in the view
<script type="text/javascript">
$(document).ready(function () {
$("#EventBerichten").change(function () {
$("#log").ajaxError(function (event, jqxhr, settings, exception) {
alert(exception);
});
var BerichtSelected = $("select option:selected").first().text();
$.get('#Url.Action("InhoudByIdPartial")',
{ EventBerichtID: BerichtSelected }, function (data) {
$("#target").html(data);
});
});
});
</script>
#{
Html.RenderAction("InhoudByIdPartial", Model.EventID);
}
<fieldset>
<legend>Berichten over dit Evenement</legend>
<div>
#Html.DropDownList("EventBerichten", new SelectList(ViewBag.EventBerichten, "EventBerichtenID", "Titel"), new { #class = "form-control", onchange = "$(this.form).submit();" })
</div>
<br />
<div id="target">
</div>
<div id="log">
</div>
</fieldset>
Thanks - this helped me to understand better ansd solve a problem I had.
The JQuery provided to get the text of selectedItem did NOT wwork for me
I changed it to
$(function () {
$("#SelectedVender").on("change", function () {
$("#SelectedvendorText").val($(**"#SelectedVender option:selected"**).text());
});
});
Simple solution not sure if this has been suggested or not. This also may not work for some things. That being said this is the simple solution below.
new SelectListItem { Value = "1", Text = "Waiting Invoices", Selected = true}
List<SelectListItem> InvoiceStatusDD = new List<SelectListItem>();
InvoiceStatusDD.Add(new SelectListItem { Value = "0", Text = "All Invoices" });
InvoiceStatusDD.Add(new SelectListItem { Value = "1", Text = "Waiting Invoices", Selected = true});
InvoiceStatusDD.Add(new SelectListItem { Value = "7", Text = "Client Approved Invoices" });
#Html.DropDownList("InvoiceStatus", InvoiceStatusDD)
You can also do something like this for a database driven select list. you will need to set selected in your controller
#Html.DropDownList("ApprovalProfile", (IEnumerable<SelectListItem>)ViewData["ApprovalProfiles"], "All Employees")
Something like this but better solutions exist this is just one method.
foreach (CountryModel item in CountryModel.GetCountryList())
{
if (item.CountryPhoneCode.Trim() != "974")
{
countries.Add(new SelectListItem { Text = item.CountryName + " +(" + item.CountryPhoneCode + ")", Value = item.CountryPhoneCode });
}
else {
countries.Add(new SelectListItem { Text = item.CountryName + " +(" + item.CountryPhoneCode + ")", Value = item.CountryPhoneCode,Selected=true });
}
}
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.
I have two dropdown lists. And whant to make them Cascading. Here is the viewModel:
public class FaqOverviewModel
{
public int Id { get; set; }
public string EmailBericht { get; set; }
public string Naam { get; set; }
public string AfzenderNaam { get; set; }
public string TelefoonNr { get; set; }
[ForeignKey("FaqCategorie")]
public int FaqCategorie_Id { get; set; }
public FaqOverviewModel()
{
Categorie = new List<FaqCategorie>();
SubCategorie = new List<FaqSubCategorie>();
}
public FaqOverviewModel(IEnumerable<FaqCategorie> categories)
{
this.Categorie = categories;
//this.SubCategorie = subcategorie;
}
#region FAQCategorie
private readonly IEnumerable<FaqCategorie> Categorie;
private readonly IEnumerable<FaqSubCategorie> SubCategorie;
//private IOrderedQueryable<FaqCategorie> categories;
private IEnumerable<SelectListItem> subCategorie;
public int? SelectedCategoriedFaqId { get; set; }
public int? SelectedSubCategorieFaqId { get; set; }
public IEnumerable<SelectListItem> FAQCategorieItems
{
get
{
return new SelectList(Categorie, "Id", "Naam");
}
}
#endregion
#region subcategorie
#endregion
}
And the Contoller:
public class FAQController : Controller
{
//FaqService faqService;
FaqCategorieService faqCategorieService;
FaqCategorieSubService faqCategorieSubService;
public FAQController(FaqCategorieService faqCategorieService, FaqCategorieSubService faqCategoriesubservice)
{
this.faqCategorieService = faqCategorieService;
this.faqCategorieSubService = faqCategoriesubservice;
}
// GET: FAQ
// [HttpGet]
public ActionResult Index()
{
var categories = faqCategorieService.GetAll().OrderBy(x => x.Naam);
// var subCategorie = faqCategorieSubService.GetAll().OrderBy(sub => sub.Naam);
//var subCategorie = faqCategorieSubService.GetAll().Where(s => s.Id == s.FaqCategorie_Id).ToList()
// .Select(c => new SelectListItem() { Value = c.Id.ToString(), Text = c.Naam });
FaqOverviewModel model = new FaqOverviewModel(categories);
return View(model);
}
public JsonResult SubCategorie(int Categorieid)
{
var subCategorie = faqCategorieSubService.GetAll().Where(s => s.Id == Categorieid).ToList()
.Select(c => new SelectListItem() { Value = c.Id.ToString(), Text = c.Naam });
//var Subcategorie = faqCategorieSubService.GetAll().Where(s => s.Id == Categorieid).ToList()
// .Select(c => new SelectListItem)(){ = c.Id.ToString(), Text = c.Naam });
return this.Json(subCategorie, JsonRequestBehavior.AllowGet);
}
}
And the View:
#using (Html.BeginForm())
{
#*#Html.DropDownList("Id", ViewBag.Id as SelectList, "Select a Category", new { id = "FaqCategorie_Id" })<br />
<select id="FaqSubCategorie" name="FaqSubCategorie"></select><br />*#
<p>
<span class="fixedLabelWidth">#Html.LabelFor(model => model.SelectedCategoriedFaqId, "Categorie:")</span>
#Html.DropDownListFor(x => x.SelectedCategoriedFaqId, Model.FAQCategorieItems)
<select name="Id" id="Id"></select>
</p>
#*<p>
<span class="fixedLabelWidth">#Html.LabelFor(model => model.SelectedSubCategorieFaqId, "onderwerp:")</span>
#Html.DropDownListFor(x => x.SelectedSubCategorieFaqId, Model.FaqCategorieSubItems)
</p>*#
<p>
<span class="fixedLabelWidth">#Html.LabelFor(model => model.EmailBericht, "Bericht:")</span>
#Html.TextAreaFor(x => x.EmailBericht)
</p>
<p>
<span class="fixedLabelWidth">#Html.LabelFor(model => model.AfzenderNaam, "Afzender:")</span>
#Html.TextBoxFor(x => x.AfzenderNaam)
</p>
<p>
<span class="fixedLabelWidth">#Html.LabelFor(model => model.TelefoonNr, "Tel:")</span>
#Html.TextBoxFor(x => x.TelefoonNr)
</p>
}
#section scripts
{
#Scripts.Render("~/bundles/jquery")
#Scripts.Render("~/bundles/Form")
#Scripts.Render("~/bundles/jqueryval")
#Scripts.Render("~/Bundles/Q")
#Scripts.Render("~/Bundles/moment")
#Scripts.Render("~/bundles/Utils")
#Scripts.Render("~/bundles/Jquery-ui")
<script type="text/javascript">
$(document).ready(function () {
$("#Id").change(function () {
var strStateID = "";
strCategorieID = $(this)[0].value; // get the selected categorie id
var url = Medicijnverstrekking.baseUrl + "/FAQ/SubCategorie/" + strCategorieID;
// call controller's action
$.getJSON(url, null, function (data) {
// do something once the data is retrieved
$("#Id").empty();
$.each(data, function (index, optionData) {
$("#Id").append("<option value='"
+ optionData.Id
+ "'>" + optionData.Naam
+ "</option>");
});
});
})
.change(); // value});
});
</script>
}
The first dropdownlist is filled. But the second dropdownlist is empty.And also the Json:
public JsonResult SubCategorie(int Categorieid) doesnt hit, when I put a breakpoint there
Thank you
I'm newbie in MVC (MVC4) and I have this problem:
I need one view to show Listbox data on left and form to add/edit on right of this view.
Problem is: when I select on listbox then click "Edit", no data to show on Edit form.
screen for this question
My View and Code are bellow:
My View Name AddZone (Addzone.cshtml):
#model CTN_MVC.Models.Zone
#{
ViewBag.Title = "AddZone";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Zone Management
</h2>
<p></p>
#using (Html.BeginForm())
{
#Html.ValidationSummary(true)
<div style="float: right">
<fieldset>
<legend>AddZone</legend>
<div class="editor-label">
#Html.LabelFor(model => model.Name)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Name)
#Html.ValidationMessageFor(model => model.Name)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.ParentID)
</div>
<div class="editor-field">
#Html.DropDownList("parentzone", new SelectList(new CTN_MVC.Controllers.AdminController().ShowParentZone((string)ViewBag.ParentZoneSelect), "Value", "Text"), " -- Choice Zones -- ", new { style = "width:312px" })
</div>
<p>
<button name="zoneaction" title="Update" value="zone_add" >Update</button>
</p>
</fieldset>
</div>
<div style="float: left">
#{Html.RenderPartial("ListZones");}
</div>
}
Here is ListZone.cshtml
#Html.ListBox("listzone", new CTN_MVC.Controllers.AdminController().ShowListZone((string[])ViewBag.ZoneSelect), new { size = "15", multiple = "multiple", style = "width:450px" })
<br />
<br />
<table>
<tr>
<td>
<button title="Sửa" value="zone_edit" name="zoneaction">Edit</button>
</td>
<td>
<button title="Xóa" value="zone_del" name="zoneaction">Delete</button>
</td>
</tr>
</table>
And my Code in Controller:
[Authorize]
public ActionResult AddZone()
{
return View();
}
[HttpPost]
[Authorize]
public ActionResult AddZone(Zone input, string zoneaction, string[] listzone, string parentzone)
{
if (zoneaction == "zone_del")
{
foreach (string id in listzone)
{
mghelper.Delete<Zone>(TableNames.Zone, "ZoneID", id);
}
return RedirectToAction("AddZone");
}
else if (zoneaction == "zone_edit")
{
input = mghelper.GetInfo<Zone>(TableNames.Zone, "ZoneID", listzone[0])[0];
ViewBag.ParentZoneSelect = input.ParentID.ToString();
return View("AddZone", input);
}
else
{
if(input.ZoneID > 0)
{
input.ParentID = Utility.ConvertToInt(parentzone);
input.DateCreate = DateTime.UtcNow;
input.AdminID = CurrentAdmin._id;
mghelper.Updates<Zone>(input, TableNames.Zone);
}
else
{
List<Zone> mtinfo = mghelper.GetLast<Zone>(TableNames.Zone, "DateCreate", 0);
if (mtinfo == null || mtinfo.Count < 1)
input.ZoneID = 1;
else
input.ZoneID = mtinfo[0].ZoneID + 1;
input.ParentID = Utility.ConvertToInt(parentzone);
input.DateCreate = DateTime.UtcNow;
mghelper.Insert<Zone>(input, TableNames.Zone);
}
return RedirectToAction("AddZone");
}
}
public string ZoneSelect { get; set; }
public string ParentZoneSelect { get; set; }
public IEnumerable<SelectListItem> ShowListZone(string[] id)
{
if (id == null)
{
id = new string[1];
id[0] = "0";
}
var allFlavors = GetListZone(id).Select(f => new SelectListItem
{
Value = f.ZoneID.ToString(),
Text = f.ZoneName,
Selected = f.isSelected
});
return allFlavors;
}
public class SelectZone
{
public string ZoneName { get; set; }
public string ZoneID { get; set; }
public bool isSelected { get; set; }
}
public IEnumerable<SelectListItem> ShowParentZone(string id)
{
if (id == null) id = "0";
string[] lid = new string[1];
lid[0] = id;
var allFlavors = GetListZone(lid).Select(f => new SelectListItem
{
Value = f.ZoneID.ToString(),
Text = f.ZoneName,
Selected = f.isSelected
});
return allFlavors;
}
public List<SelectZone> GetListZone(string[] lid)
{
var query = Query.EQ("ParentID", 0);
List<Zone> lz = mghelper.GetByCondition<Zone>(TableNames.Zone,query, 0,false);
List<SelectZone> lsz = new List<SelectZone>();
foreach (Zone z in lz)
{
SelectZone sl = new SelectZone();
sl.ZoneName = z.Name;
sl.ZoneID = z.ZoneID.ToString();
bool checksl = false;
foreach (string id in lid)
{
if (z.ZoneID.ToString() == id)
{
checksl = true;
}
}
sl.isSelected = checksl;
lsz.Add(sl);
//RecruiListZone(lsz, z.ZoneID, lid);
}
return lsz;
}
Please help me. (I'm sorry for my english is not good)
You need to call the GetZone when you click Edit. I believe as of now you are your form simply makes a POST to the same action which was used to load the page.
Add a new action method to return the selected zone detail
In your case, you could start using jQuery ajax and load the Partial view in the right hand side.
Below is the sample code to load zone detail
Controller
[HttpPost]
public ActionResult GetZone(string id)
{
//load your model
return PartialView("ZoneDetail.cshtml",model);
}
jQuery
$(document.ready(function(){
$('#edit-zone').click(function(){
$.post('/Zone/GetZone',{id:selectedId}, function(data){
$('#zone-detail-container').html(data);
});
});
});