Load partial view on ajax success - javascript

I am trying to generate checkbox dynamically(image: Select Report) on change/click event of another checkbox(image:Report Type) by using pertial view.On page load I made one checkbox true and generate checkbox dynamically based on it's data.
Here is the image of this page:
But when I click another checkbox, It's not updating the panel and showing previous data. Here is the image:
Here is my Index Page
#using RSDMS.ViewModel
#{
ViewBag.Title = "Reports";
Layout = "~/Views/ReportModule/_ReportModule.cshtml";
var ReportTypeList = (IEnumerable<VmReportType>)ViewBag.ReportType;
}
<script src="~/Scripts/jquery.unobtrusive-ajax.js"></script>
<h2 style="color: #317eac; margin-top: -8% !important">Reports </h2>
<div class="panel panel-info class" style="margin-top: 0 !important;width: 99%">
<div class="panel-heading" style="background: #1995dc; text-decoration: solid;">Report Type</div>
<div class="panel-body reportTypeDiv">
#using (#Html.BeginForm(new { id = "reportType" }))
{
if (ReportTypeList != null)
{
<table>
<tr>
#foreach (var p in ReportTypeList)
{
<td>
#Html.CheckBoxFor(it => p.IsCheck, new { Style = "vertical-align:3px", value = p.Id, #class = "checkbox"})
</td>
<td>
#Html.HiddenFor(it => p.Id)
#Html.DisplayFor(it => p.Name)
</td>
}
</tr>
</table>
}
}
</div>
</div>
<div class="panel panel-info class" style="height: 650px; width: 300px">
<div class="panel-heading" style="background: #1995dc; text-decoration: solid;">Select Report</div>
<div class="panel-body listReport" id="lstReport">
#Html.Partial("_ListOfReports")
</div>
<div class="CrystalReport">
<iframe class="CrystalReportViewer1"> </iframe>
</div>
</div>
<script type="text/javascript">
$(function () {
$('.checkbox').change(function () {
var selectedValue = this.value;
$('input:checkbox:checked').each(function () {
if (this.value == selectedValue) {
$(this).attr('checked', 'checked');
} else {
$(this).removeAttr('checked');
}
});
$(this).attr('checked', 'checked');
$.ajax({
url: '#Url.Action("LoadReports", "Reports", new AjaxOptions { UpdateTargetId = "lstReport" })',
type: 'POST',
data: { Id: selectedValue },
success: function () {
swal("ok", " ", "success");
},
error: function () {
sweetAlert("not ok", " ", "error");
}
});
});
});
</script>
Here is my Partial Page
#using RSDMS.ViewModel
#{
var ReportList = (IEnumerable<VmReport>)ViewBag.ListOfReports;
}
#using (#Html.BeginForm())
{
if (ReportList != null)
{
foreach (var q in ReportList)
{
<table id="selectReport">
<tr>
<td>
#Html.CheckBoxFor(it => q.IsChecked, new { Style = "vertical-align:3px}", type = "checkbox", value = q.ReportId, #class ="checkboxReport" })
</td>
<td>
#Html.HiddenFor(it => q.ReportId)
#Html.DisplayFor(it => q.Name)
</td>
</tr>
</table>
}
}
}
Here is my controller's Code
public ActionResult Index()
{
var listReportType = new List<VmReportType>
{
new VmReportType{Id = "A", Name = "A-Road Related", IsCheck = true},
new VmReportType{Id = "B", Name = "B- Road+Structure Related", IsCheck = false},
new VmReportType{Id = "C", Name = "C- Need, Scheme & Progress Related", IsCheck = false},
new VmReportType{Id = "D", Name = "D- GC/RM/etc. Related", IsCheck = false},
new VmReportType{Id = "E", Name = "E- RIMMU", IsCheck = false}
};
ViewBag.ReportType = listReportType;
LoadReports("A");
return PartialView();
}
[HttpPost]
public ActionResult LoadReports(string id)
{
var reports = _manager.LoadReports(id);
ViewBag.ListOfReports = reports;
return PartialView("_ListOfReports", ViewBag.ListOfReports);
}
Here is the image of ajax response

Related

Dropdownlist as selected in ASP.NET MVC using ViewBag?

I want to display dropdownlist in Bootstrap Modal When I click on button add it displays this error ( Server Error in '/' Application. There is no ViewData item of type 'IEnumerable' that has the key 'DepartmentId'.)
it returns the NULL value someone help me to solve this problem
In Controller:
Database1Entities db = new Database1Entities();
public ActionResult Index()
{
List<Department> DeptList = db.Departments.ToList();
ViewBag.ListOfDepartment = new SelectList(DeptList, "DepartmentId", "DepartmentName");
return View();
}
public ActionResult GetStudent()
{
List<StudentViewModel> data = db.Students.Select(x => new StudentViewModel
{
StudentId =x.StudentId,
FirstName = x.FirstName,
LastName = x.LastName,
DepartmentName = x.Department.DepartmentName,
}).ToList();
return Json(new { data = data }, JsonRequestBehavior.AllowGet);
}
public ActionResult GetStudentPartial(int? id)
{
var student = db.Students.Find(id) ?? new Student();
return PartialView("_CreateOrUpdateStudentPartial", student);
}
public ActionResult CreateOrUpdateStudent(Student student)
{
if (ModelState.IsValid)
{
if (student.StudentId > 0)
{
db.Entry(student).State = System.Data.Entity.EntityState.Modified;
}
else
{
db.Students.Add(student);
}
db.SaveChanges();
return Json(true, JsonRequestBehavior.AllowGet);
}
return Json(false, JsonRequestBehavior.AllowGet);
}
public ActionResult Delete(int id)
{
try
{
var student = db.Students.Find(id);
db.Students.Remove(student);
db.SaveChanges();
return Json(true, JsonRequestBehavior.AllowGet);
}
catch (Exception)
{
return Json(false, JsonRequestBehavior.AllowGet);
}
}
Partial View:
#model Example1.Models.Student
<form name="studentForm">
<div class="modal-header">
<h5 class="modal-title">
Modal title
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
</h5>
</div>
<div class="modal-body">
#Html.HiddenFor(x => x.StudentId)
<div class="row">
<div class="col-md-12">
<div class="col-md-6">
<div class="form-group">
<label>First Name</label>
#Html.EditorFor(x => x.FirstName, new { htmlAttributes = new { #class = "form-control", #placeholder = "First Name*", Required = true } })
#Html.ValidationMessageFor(x => x.FirstName, "", new { #class = "text-danger" })
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label>Last Name</label>
#Html.EditorFor(x => x.LastName, new { htmlAttributes = new { #class = "form-control", #placeholder = "Last Name*", Required = true } })
#Html.ValidationMessageFor(x => x.LastName, "", new { #class = "text-danger" })
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label>Department Name</label>
#Html.DropDownListFor(m => m.DepartmentId, ViewBag.ListOfDepartment as SelectList, "--Select Dept--", new { #id = "DropDwn", #class = "form-control" })
</div>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-sm pull-left" data-dismiss="modal">Cancel</button>
<button type="button" onclick="createOrUpdate()" class="btn btn-success pull-left">Save</button>
</div>
</form>
View:
<div style="width:90%; margin:0 auto" class="tablecontainer">
<p><button type="button" class="btn btn-sm btn-success" onclick="getStudent()">Add New Student</button></p>
<table id="myDatatable" class="table table-striped table-bordered" style="width:100%">
<thead>
<tr>
<th>FirstName</th>
<th>LastName</th>
<th>DepartmentName</th>
<th>Edit</th>
<th>Delete</th>
</tr>
</thead>
</table>
</div>
<div class="modal fade" role="dialog" id="studentModal" aria-labelledby="studentModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content" id="studentmodalBody">
</div>
</div>
</div>
Script:
<script>
var datatable;
$(document).ready(function () {
datatable = $('#myDatatable').DataTable({
"ajax": {
"url": '/home/GetStudent',
"type": "get",
"datatype": "json"
},
"columns": [
{ "data": "FirstName", "autoWidth": true },
{ "data": "LastName", "autoWidth": true },
{
"data": "DepartmentName", "render": function (data) {
return data;
}
},
{
"data": "StudentId", "width": "50px", "render": function (data) {
return '<button class="btn btn-success" onclick="getStudent(' + data + ')">Edit</button>';
}
},
{
"data": "StudentId", "width": "50px", "render": function (data) {
return '<button class="btn btn-danger" onclick="Delete(' + data + ')">Delete</button>';
}
},
]
})
})
function getStudent(id) {
$.get("/Home/GetStudentPartial", { id: id }, function (res) {
$("#studentmodalBody").html(res);
$("#studentModal").modal('show');
})
}
function createOrUpdate() {
var modal = $("#studentModal");
var form = $('form[name= "studentForm"]');
form.validate();
if (!form.valid()) {
return;
} else {
var data = form.serialize();
$.post("/home/CreateOrUpdateStudent", data, function (res) {
if (res) {
modal.modal('hide');
datatable.ajax.reload();
}
})
}
}
function Delete(id) {
if (confirm("Are you sure ? ") == true) {
$.get("/Home/Delete", { id: id }, function (res) {
if (res) {
datatable().ajax.reload();
}
})
}
}
</script>
If your DeptList is not null, try change code below :
#Html.DropDownListFor(m => m.DepartmentId, ViewBag.ListOfDepartment as SelectList, "--Select Dept--", new { #id = "DropDwn", #class = "form-control" })
to:
#Html.DropDownListFor(m => m.DepartmentId, ViewBag.ListOfDepartment as IEnumerable<SelectListItem>, "--Select Dept--", new { #id = "DropDwn", #class = "form-control" })
EDIT: I've just realized that you are filling your ViewBag in the Index() method but your are calling it in _CreateOrUpdateStudentPartial and you can't do that. ViewBag is not tranffering data between views.
public ActionResult GetStudentPartial(int? id)
{
var student = db.Students.Find(id) ?? new Student();
// you need to add here
List<Department> DeptList = db.Departments.ToList();
ViewBag.ListOfDepartment = new SelectList(DeptList,"DepartmentId","DepartmentName");
return PartialView("_CreateOrUpdateStudentPartial", student);
}

Cascaded Drop Down List with search box

I'm trying to use cascaded Drop Down for a project, but with a bit of a twist. For Power Users, they can enter a stock code and search. The retrieved information then updates the Parent Drop Down and the cascaded Drop Down selection.
Using a click event, I can search the entered value and it returns all the needed information. I can update the Parent to Display the correct information, But unable to get the child to display. It's stuck on showing " -- Select --" Populating the drop down's with data to select from works great. Could really use some insight and help.. Got myself stumped on the child. Thanks..
I followed this example to setup the Dropdowns. asp.net MVC cascading dropdown lists
<Controller>
public ActionResult Create()
{
ViewData["User"] = User.Identity.GetUserName();
BindPartType();
return View();
}
public void BindPartType()
{
partsmanagementEntities5 parttypelist = new partsmanagementEntities5(); //Parts
var parttype = parttypelist.parttypes.ToList();
List<SelectListItem> pli = new List<SelectListItem>();
pli.Add(new SelectListItem { Text = "--Select Catagory--", Value = "0" });
foreach (var m in parttype)
{
pli.Add(new SelectListItem { Text = m.PartType1, Value = m.idPartType.ToString() });
ViewBag.PartType = pli;
}
}
public JsonResult GetInventory(int? id)
{
partsmanagementEntities5 partlist = new partsmanagementEntities5();
var ddlpart = partlist.parts.Where(x => x.PartType == id).ToList();
List<SelectListItem> lipart = new List<SelectListItem>();
lipart.Add(new SelectListItem { Text = "--Select Inventory--", Value = "0" });
if (ddlpart != null)
{
foreach (var x in ddlpart)
{
lipart.Add(new SelectListItem { Text = x.PartDescription, Value = x.idParts.ToString() });
}
}
return Json(new SelectList(lipart, "Value", "Text", JsonRequestBehavior.AllowGet));
}
public JsonResult Check(string id)
{
partsmanagementEntities5 partlist = new partsmanagementEntities5();
StringBuilder test = new StringBuilder();
if(id != null && id != "")
{
foreach (char c in id)
{
if (!char.IsNumber(c))
test.Append(c);
}
var ddlpartnumber = partlist.parts.Where(x => x.PartNumber == id.ToString());
PartDetails li = new PartDetails();
foreach (var item in ddlpartnumber.ToList())
{
li.PartNumber = item.PartNumber;
li.PartPrice = item.PartPrice;
li.idParts = item.idParts;
li.EHF = item.EHF;
li.PartDescription = item.PartDescription;
li.PartImage = item.PartImage;
li.partImageContentType = item.partImageContentType;
li.unit = item.unit;
li.PartType = item.PartType;
li.VendorPartNumber = item.VendorPartNumber;
}
return Json(li, JsonRequestBehavior.AllowGet);
}
return Json("", JsonRequestBehavior.AllowGet);
}
<View>
<table>
<tr>
<td style="padding-left:0.8ex;padding-top:0.8ex">#Html.Label("Catagory: ")</td>
<td>
#Html.DropDownListFor(model => model.PartType, ViewBag.PartType as List<SelectListItem>, new { style = "width: 800px;" })
#Html.ValidationMessageFor(model => model.PartType, "", new { #class = "text-danger" })
</td>
<td style="padding-left:6ex;padding-top:0.8ex"></td>
</tr>
<tr>
<td style="width:1px;white-space:nowrap;padding-left:0.8ex">#Html.Label("Inventory: ")</td>
<td>
#Html.DropDownListFor(model => model.PartNumber, new SelectList(string.Empty, "Value", "Text"), "--Select Inventory--", new { style = "width:900px" })
#Html.ValidationMessageFor(model => model.PartNumber, "", new { #class = "text-danger" })
</td>
</tr>
<tr>
<td style="width:1px;white-space:nowrap;padding-left:6ex">#Html.Label("Or choose:")</td>
</tr>
<tr>
<td style="width:1px;white-space:nowrap;padding-left:0.8ex">#Html.Label("Enter Valid Part #: ")</td>
<td><input type="text" name="CheckPartNumber" id="CheckPartNumber"> <input type="button" id="Search" value="Search" class="btn btn-default" />
</tr>
</table>
<script src="~/Scripts/jquery-3.0.0.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$("#PartType").change(function () {
$("#PartNumber").empty();
$.ajax({
type: 'POST',
url: '#Url.Action("GetInventory", "partrequests")',
dataType: 'json',
data: { id: $("#PartType").val() },
success: function (PartNumber) {
$.each(PartNumber, function (i, PartNumber) {
$("#PartNumber").append('<option value="'
+ PartNumber.Value + '">'
+ PartNumber.Text + '</option>');
});
},
error: function (ex) {
alert('Failed.' + ex);
}
});
return false;
})
});
$(document).ready(function () {
$("#Search").click(function () {
$.ajax({
type: 'POST',
url: '#Url.Action("Check","partrequests")',
dataType: 'json',
data: { id: $("#CheckPartNumber").val() },
success: function (Data) {
var selectedValue = Data.PartType
$('#PartType option').map(function () {
if ($(this).val() == selectedValue) return this;
}).attr('selected', 'selected').change();
var selectedValue2 = Data.idParts;
$('#PartNumber option').map(function () {
if ($(this).val() == selectedValue2) return this;
}).attr('selected', 'selected');
},
error: function (ex) {
alert('Failed.' + ex);
}
});
return false;
})
});
</script>

Cascading dropdown list does not bind data to the 2nd dropdown

I have a main view. Once the posting is done, it will render a partial view in the main view.
My partial view has a cascading dropdown list that changes the 2nd DropdownList items based on the selected value from the 1st DropdownList.
Here is my Dropdown in my Partial View.
#model MigratingDB.Models.ViewModel
<script src="~/Scripts/jquery-1.10.2.js"></script>
<script src="~/Scripts/jquery.unobtrusive-ajax.js"></script>
<div>
#Html.DropDownListFor(m => m.DropdownViewModel.SelectedValue1,
Model.DropdownViewModel.List1, "Select",htmlAttributes: new { #class = "form-control", #id = "ddl1" })
</div>
<div>
#Html.DropDownListFor(m => m.DropdownViewModel.SelectedValue2,
Model.DropdownViewModel.List2 = new SelectList(Enumerable.Empty<SelectListItem>()), "Select",
htmlAttributes: new { #class = "form-control", #id = "ddl2" })
</div>
The script I tried based from this.
<script>
$(function () {
$('#ddl1').change(function () {
$("#ddl2").empty();
var selectedValue = $(this).val();
$.ajax({
url: '#Url.Action("Getddl2Items", "Controller")',
type: "POST",
dataType: 'json',
data: { id: selectedValue },
success: function (value) {
$.each(value, function (i, val) {
$("#ddl2").append('<option value="' + val.Value + '">' +
val.Text + '</option>');
});
},
error: function (ex) {
alert('Failed' + ex);
},
});
});
});
</script>
In my Controller:
[HttpPost]
public ActionResult Foo (ViewModel vm)
{
// Dropdownlist
var list1 = // get items frop ddl1
vm.DropdownViewModel.List1= new SelectList(list1, "Value", "Text");
return PartialView("_PartialView", vm);
}
// Get ddl2 Items
public JsonResult Getddl2Items (int id)
{
var ViewModel = new ViewModel();
var list2= // get ddl2 items from the database
ViewModel.DropdownViewModel.List2= new SelectList(list2, "Value", "Text");
return Json(ViewModel.DropdownViewModel.List2, JsonRequestBehavior.AllowGet);
}
Every time I tried to select a value from the ddl1, it errors and show
Failed [object Object].
What causes this?
This is a long post that I tested and works. Since it is long, you can pick out the parts you need. Let's work together to figure out why it is not working for you.
This will be your table and data creation:
--Use your database name instead of Breaz
USE [Breaz]
GO
/****** Object: Table [dbo].[tblCity] Script Date: 7/17/2017 9:46:31 AM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[tblCity](
[Cityid] [int] NOT NULL,
[CityName] [nvarchar](50) NULL,
[stateid] [int] NOT NULL
) ON [PRIMARY]
GO
/****** Object: Table [dbo].[tblState] Script Date: 7/17/2017 9:46:31 AM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[tblState](
[stateid] [int] NOT NULL,
[statename] [nvarchar](50) NULL,
PRIMARY KEY CLUSTERED
(
[stateid] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
INSERT [dbo].[tblCity] ([Cityid], [CityName], [stateid]) VALUES (1, N'Phoenix', 1)
INSERT [dbo].[tblCity] ([Cityid], [CityName], [stateid]) VALUES (2, N'Las Angeles', 2)
INSERT [dbo].[tblState] ([stateid], [statename]) VALUES (1, N'Arizona')
INSERT [dbo].[tblState] ([stateid], [statename]) VALUES (2, N'California')
ALTER TABLE [dbo].[tblCity] WITH CHECK ADD FOREIGN KEY([stateid])
REFERENCES [dbo].[tblState] ([stateid])
GO
Create your edmx, by going through visual studio wizard.
Create your view model:
//user your namespace
namespace Testy20161006.Models
{
public class Registration
{
[Required(ErrorMessage = "Enter State")]
public string State { get; set; }
[Required(ErrorMessage = "Enter City")]
public string City { get; set; }
}
}
Your controller/classes:
public class HomeController : Controller
{
public JsonResult getCity(int id)
{
//use your dbcontext name from edmx wizard
using (BreazEntities33 objEF = new BreazEntities33())
{
var ddlCity = objEF.tblCities.Where(x => x.stateid == id).ToList();
List<SelectListItem> licities = new List<SelectListItem>();
licities.Add(new SelectListItem { Text = "--Select State--", Value = "0" });
if (ddlCity != null)
{
foreach (var x in ddlCity)
{
licities.Add(new SelectListItem { Text = x.CityName, Value = x.Cityid.ToString() });
}
}
return Json(new SelectList(licities, "Value", "Text", JsonRequestBehavior.AllowGet));
}
}
[HttpPost]
public ActionResult IndexStackOverflow(Registration registration)
{
//put breakpoint here to see values coming back from view
return View(registration);
}
//use your name of action that starts the process, named in routeconfig.cs
public ActionResult IndexStackOverflow()
{
bindState();
return View();
}
public void bindState()
{
//use your dbcontext name from edmx wizard
using (BreazEntities33 objEF = new BreazEntities33())
{
var state = objEF.tblStates.ToList();
List<SelectListItem> li = new List<SelectListItem>();
li.Add(new SelectListItem { Text = "--Select State--", Value = "0" });
foreach (var m in state)
{
li.Add(new SelectListItem { Text = m.statename, Value = m.stateid.ToString() });
ViewBag.state = li;
}
}
}
Here is your view:
#model Testy20161006.Models.Registration
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>IndexStackOverflow</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap-theme.min.css">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$("#State").change(function () {
$("#City").empty();
$.ajax({
type: 'POST',
url: '#Url.Action("getcity")',
dataType: 'json',
data: { id: $("#State").val() },
success: function (city) {
$.each(city, function (i, city) {
$("#City").append('<option value="'
+ city.Value + '">'
+ city.Text + '</option>');
});
},
error: function (ex) {
alert('Failed.' + ex);
}
});
return false;
})
});
</script>
</head>
<body>
#using (Html.BeginForm())
{
<div class="container">
<div class="row">
<div class="form-group">
#Html.LabelFor(model => model.State, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.State, ViewBag.state as List<SelectListItem>, new { style = "width: 200px;" })
#Html.ValidationMessageFor(model => model.State, "", new { #class = "text-danger" })
</div>
</div>
</div>
</div>
<div class="container">
<div class="row">
<div class="form-group">
#Html.LabelFor(model => model.City, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.City, new SelectList(string.Empty, "Value", "Text"), "--Select City--", new { style = "width:200px" })
#Html.ValidationMessageFor(model => model.City, "", new { #class = "text-danger" })
</div>
</div>
</div>
</div>
<div><input type="button" value="submit" /></div>
}
</body>
</html>
Here is an example that returns Json value from a SelectListItem in a ViewModel.
public class ReturnJsonVM
{
public List<SelectListItem> licities = new List<SelectListItem>();
}
public class HomeController : Controller
{
//use your name of action that starts the process, named in routeconfig.cs
public string IndexStackOverflow()
{
using (BreazEntities33 objEF = new BreazEntities33())
{
var ddlCity = objEF.tblCities.Where(x => x.stateid == 1).ToList();
List<SelectListItem> licities = new List<SelectListItem>();
ReturnJsonVM returnJsonVM = new ReturnJsonVM();
if (ddlCity != null)
{
foreach (var x in ddlCity)
{
returnJsonVM.licities.Add(new SelectListItem { Text = x.CityName, Value = x.Cityid.ToString() });
}
}
string json = JsonConvert.SerializeObject(returnJsonVM.licities);
//put your break point here to see example that return Json value from SelectListItem in ViewModel
return json;
}
}

How to filter information in a dropdown depending on the first selection of another dropdown [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I have a problem filtering information in a second dropdown, that information should depend on the first selection of the first dropdown, I would like to know how I can filter that information
This is my code:
c# Controller:
[HttpGet]
public IActionResult SubTrails()
{
try
{
var n = _unitOfWork.SubTrails.GetAll().ToList();
if (n == null)
{
return NoContent();
}
return new ObjectResult(n);
}
catch (Exception ex)
{
_logger.LogError(ex.ToString());
return StatusCode(StatusCodes.Status500InternalServerError, new { Message = "Internal Server Error" });
}
}
[HttpGet]
public IActionResult Levels()
{
try
{
var n = _unitOfWork.Levels.GetAll().ToList();
if (n == null)
{
return NoContent();
}
return new ObjectResult(n);
}
catch (Exception ex)
{
_logger.LogError(ex.ToString());
return StatusCode(StatusCodes.Status500InternalServerError, new { Message = "Internal Server Error" });
}
}
[HttpGet]
public IActionResult Trails()
{
try
{
var n = _unitOfWork.Trails.GetAll().ToList();
if (n == null)
{
return NoContent();
}
return new ObjectResult(n);
}
catch (Exception ex)
{
_logger.LogError(ex.ToString());
return StatusCode(StatusCodes.Status500InternalServerError, new { Message = "Internal Server Error" });
}
}
cshtml:
#model DefinityFirst.Mobile.Admin.Web.Services.Marvel.Contracts.ListTrailSubTrailLevelContract
#inject DefinityFirst.Mobile.Admin.Web.Services.Marvel.IMarvelServices DropDownDataHelper
#{
ViewBag.Title = "Create";
}#if (!ViewData.ModelState.IsValid)
{
<div class="alert alert-danger alert-dismissible" role="alert">
<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>
<strong>Warning!</strong> #Html.ValidationMessage("Error")
</div>
}
<h2>Create</h2>
<p>New TrailSubTRailLEvel</p>
#using (Html.BeginForm("TrailSubTrailLevel", "TrailSubTrailLevel", FormMethod.Post, new { id = "demoForm" }))
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Trail</h4>
<div class="form-group">
#Html.Label("", "Trail", new { #class = "control-label col-md-2" })
<div class="col-md-10" id = "partialDiv">
#*#Html.DropDownListFor(model => model.TrailContract.Responsable.Id, Model.ManagersList, "Select one", new { #class = "form-control" })*#
#Html.DropDownListFor(model => model.TrailId, await DropDownDataHelper.GetTrailsDdl(), "Select one", new { #class = "form-control", onchange = "SelectedIndexChanged()" })
#Html.ValidationMessageFor(model => model.TrailId, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.Label("", "SubTrail", new { #class = "control-label col-md-2", #name = "Subtrail", #id= "Subtrail" })
<div class="col-md-10">
#*#Html.DropDownListFor(model => model.TrailContract.Responsable.Id, Model.ManagersList, "Select one", new { #class = "form-control" })*#
#Html.DropDownListFor(model => model.SubtrailId, await DropDownDataHelper.SubTrailDdl(), "Select one", new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.SubtrailId, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.Label("", "Level", new { #class = "control-label col-md-2", #name = "Level", #id = "Level" })
<div class="col-md-10">
#*#Html.DropDownListFor(model => model.TrailContract.Responsable.Id, Model.ManagersList, "Select one", new { #class = "form-control" })*#
#Html.DropDownListFor(model => model.LevelId, await DropDownDataHelper.LevelsDdl(), "Select one", new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.LevelId, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-success" />
</div>
</div>
</div>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
#section Scripts {
<script type="text/javascript">
$('#SubtrailId').hide();
$('#LevelId').hide();
$("#Subtrail").hide();
$("#Level").hide();
$('#TrailId').on('change', function () {
// alert("este valor es de trail", this.value)
if (this.value != 0) {
$("#Subtrail").show();
$('#SubtrailId').show();
alert(this.value)
} else {
$('#SubtrailId').hide();
$('#LevelId').hide();
// alert("no es diferente ")
}
})
$('#SubtrailId').on('change', function () {
//alert("este valor es de subtrail", this.value)
if (this.value != 0) {
$("#Level").show();
$('#LevelId').show();
//alert(this.value)
} else {
$('#LevelId').hide();
// alert("no es diferente ")
}
})
function SelectedIndexChanged() {
//Form post
//alert("esta validacion jala", this.value)
document.demoForm.submit();
}
</script>
}
But when I enter the view loads all the data only once and when you change options in the dropdown does not reload dataView
I have implemented cascading dropdowns in my project using unobtrusive ajax
This example is a country list populated on the server (state is also populated if country is already selected). If the country dropdown selection is changed the state list dropdown updates by ajax
CompanyInfoViewModel has these properties (some left out for brevity)
public IList<SelectListItem> AvailableCountries { get; set; }
public string CompanyCountry { get; set; } = string.Empty;
public IList<SelectListItem> AvailableStates { get; set; }
[StringLength(200, ErrorMessage = "State/Region has a maximum length of 200 characters")]
public string CompanyRegion { get; set; } = string.Empty;
In the controller I populate the initial data
var model = new CompanyInfoViewModel();
model.CompanyRegion = selectedSite.CompanyRegion;
model.CompanyCountry = selectedSite.CompanyCountry;
model.AvailableCountries.Add(new SelectListItem { Text = sr["-Please select-"], Value = "" });
var countries = await geoDataManager.GetAllCountries();
var selectedCountryGuid = Guid.Empty;
foreach (var country in countries)
{
if (country.ISOCode2 == model.CompanyCountry)
{
selectedCountryGuid = country.Id;
}
model.AvailableCountries.Add(new SelectListItem()
{
Text = country.Name,
Value = country.ISOCode2.ToString()
});
}
if (selectedCountryGuid != Guid.Empty)
{
var states = await geoDataManager.GetGeoZonesByCountry(selectedCountryGuid);
foreach (var state in states)
{
model.AvailableStates.Add(new SelectListItem()
{
Text = state.Name,
Value = state.Code
});
}
}
Requires jquery unobtrusive ajax
This is my custom unobtrusivecascade script:
$(function () {
var $elems = $('select[data-cascade-childof]');
if ($elems) {
$elems.each(function (index, ele) {
var $parent = $('#' + $(ele).data('cascade-childof'));
var serviceUrl = $(ele).data('cascade-serviceurl');
var origVal = $(ele).data('cascade-orig-val');
var selectLabel = $(ele).data('cascade-select-label');
var disableOnEmptyParent = $(ele).data('cascade-disableonemptyparent');
var emptyParentValue = $(ele).data('cascade-parent-emptyvalue');
$parent.change(function () {
$.getJSON(serviceUrl + $parent.val(), function (data) {
var items = '<option>' + selectLabel + '</option>';
$.each(data, function (i, item) {
items += "<option value='" + item.value + "'>" + item.text + "</option>";
});
$(ele).html(items);
if (origVal.length > 0) {
var found = $(ele).find("option[value=" + origVal + "]").length > 0;
if (found) {
$(ele).val(origVal);
}
}
});
if (disableOnEmptyParent) {
var emptyParent = ($parent.val() === emptyParentValue);
if (emptyParent) {
$(ele).prop("disabled", true);
}
else {
$(ele).prop("disabled", false);
}
}
});
});
}
});
The markup in the view is like this:
<div class="form-group">
<label asp-for="CompanyCountry" class="col-md-2 control-label">#sr["Country"]</label>
<div class="col-md-10">
<select id="CompanyCountry" asp-for="CompanyCountry"
asp-items="Model.AvailableCountries" class="form-control"></select>
<span asp-validation-for="CompanyCountry" class="text-danger"></span>
</div>
</div>
<div class="form-group">
<label asp-for="CompanyRegion" class="col-md-2 control-label">#sr["State"]</label>
<div class="col-md-10">
<select id="CompanyRegion" class="form-control"
asp-for="CompanyRegion"
asp-items="Model.AvailableStates"
data-cascade-childof="CompanyCountry"
data-cascade-serviceurl='#Url.Content("~/CoreData/GetStatesJson/?countryCode=")'
data-cascade-orig-val="#Model.CompanyRegion"
data-cascade-select-label="-Please select-"></select>
<span asp-validation-for="CompanyRegion" class="text-danger"></span>
</div>
</div>
Another controller is used to return the json data for the state list based on the selected country
[HttpGet]
[AllowAnonymous]
public async Task<IActionResult> GetStatesJson(
string countryCode)
{
var country = await dataManager.FetchCountry(countryCode);
List<IGeoZone> states;
if (country != null)
{
states = await dataManager.GetGeoZonesByCountry(country.Id);
}
else
{
states = new List<IGeoZone>(); //empty list
}
var selecteList = new SelectList(states, "Code", "Name");
return Json(selecteList);
}

form.valid() returns true when form is invalid

I have a form consisting of listboxes and radiobuttons. I submit the form through ajax which sends a post. The actionlink in my controller returns a partial view. If the form is invalid I don't want to clear the selected items in the listboxes, but if the form is valid then everything should be unselected. For some reason form.valid() is always true. The error message shows perfectly so I think there is nothing wrong with the validation. Here are some snippets of my code:
View: Form
<div id="researchContainer">
#using (Html.BeginForm("ResearchCompetence", "Planning", FormMethod.Post, new { #id = "researchForm" }))
{
#Html.HiddenFor(x => x.Input.PlanningId)
#Html.ValidationSummary()
<h1>#Html.Label("OverviewResearchCompetences", Labels.OverviewResearchCompetences)</h1>
<table class="table-output">
<thead>
<tr>
<td>#Html.Label("Name", Labels.Name)</td>
<td>#Html.Label("Level", Labels.Level)</td>
<td class="text-align-right"></td>
</tr>
</thead>
<tbody>
#if (Model.CurrentResearchCompetences.Count == 0)
{
<tr>
<td>#Html.Label("NoCurrentCompetencesRes", Labels.NoCurrentCompetencesRes)</td>
</tr>
}
else
{
foreach (var item in Model.CurrentResearchCompetences)
{
<tr>
<td>#item.Vtc</td>
#{
var scoreOutput = new ILVO.Services.EmployeeManagement.ScoreOutput(item.VtcLevel);
}
<td>
#scoreOutput.ToString()
#if (!scoreOutput.ToString().Equals("Gevorderd"))
{
<span class="arrow-up">
#Html.ImageLink("IncreaseLevel", "Planning", new { id = #item.Id, planningId = Model.Input.PlanningId, actionMethod = "JobCompetence" },
"/Content/arrow-icon.png", Labels.IncreaseLevel, "")
</span>
}
#if (!scoreOutput.ToString().Equals("Basis"))
{
#Html.ImageLink("DecreaseLevel", "Planning", new { id = #item.Id, planningId = Model.Input.PlanningId, actionMethod = "JobCompetence" },
"/Content/arrow-icon.png", Labels.DecreaseLevel, "")
}
</td>
<td class="text-align-right deleteLink">
#Html.ImageLink("DeleteVtc", "Planning", new { id = #item.Id, planningId = #Model.Input.PlanningId, actionMethod = "JobCompetence" },
"/Content/delete-icon.png", Labels.Delete, "")
</td>
</tr>
}
}
</tbody>
</table>
<br />
<h1>#Html.Label("AddResearchCompetence", Labels.AddResearchCompetence)</h1>
<table>
<thead>
<tr>
<td>#Html.Label("Disciplines", Labels.Disciplines)</td>
<td>#Html.Label("Organisms", Labels.Organisms) <a id="clear-organisme" class="button-clear-vtc">Clear</a></td>
<td>#Html.Label("Techniques", Labels.Techniques) <a id="clear-technique" class="button-clear-vtc">Clear</a></td>
</tr>
</thead>
<tbody>
<tr>
<td>
#Html.ListBoxFor(x => x.Input.SelectedDiscipline, Model.Disciplines, new { #class = "vtc-listbox-height", #size = 1 })
</td>
<td>
#Html.ListBoxFor(x => x.Input.SelectedOrganism, Model.Organisms, new { #class = "vtc-listbox-height" })
</td>
<td>
#Html.ListBoxFor(x => x.Input.SelectedTechnique, Model.Techniques, new { #class = "vtc-listbox-height" })
</td>
</tr>
</tbody>
</table>
<div id="after-selection-ok">
<h1>#Html.Label("ChooseLevel", Labels.ChooseLevel)</h1>
#Html.RadioButtonFor(x => x.Input.Score, 0, new { #id = "radio1" }) #Html.Label("radio1", Labels.Basic, new { #class = "radio-label" })<br />
#Html.RadioButtonFor(x => x.Input.Score, 1, new { #id = "radio2" }) #Html.Label("radio2", Labels.Intermediate, new { #class = "radio-label" })<br />
#Html.RadioButtonFor(x => x.Input.Score, 2, new { #id = "radio3" }) #Html.Label("radio3", Labels.Expert, new { #class = "radio-label" })<br />
<br />
<input class="button" type="submit" name="AddResearchCompetence" value="#Labels.Submit" />
#Html.ActionLink(Labels.GoBack, "Detail", new { id = #Model.Input.PlanningId }, new { #class = "button margin-left" })
</div>
}
Controller : Actionlink
[HttpPost]
public ActionResult ResearchCompetence(ResearchCompetenceInputModel input)
{
// do some validations
// if validations are ok = add competence else return view
return PartialView("ResearchCompetence", new ResearchCompetenceModel(researchCompetences, currentResearchCompetences, input.PlanningId));
}
My Ajax Call
$("#researchForm").submit(function () {
$.ajax({
type: 'POST',
url: '#Url.Action("ResearchCompetence")',
data: $("#researchForm").serialize(),
success: function (data) {
$("#researchContainer").html(data);
$("#researchForm").validate();
if ($("#researchForm").valid()) { // always true
$("#Input_SelectedOrganism").val('');
$("#Input_SelectedTechnique").val('');
$("input[name='Input.Score']").attr('checked', false);
}
}
});
return false;
});
I also have these scripts loaded:
#Scripts.Render("~/bundles/modernizr")
#Scripts.Render("~/Scripts/jquery-1.10.2.js")
#Scripts.Render("~/Scripts/jquery.validate.min.js")
#Scripts.Render("~/Scripts/jquery.validate.unobtrusive.js")
#Scripts.Render("~/Scripts/jquery-ui-1.10.3.js")
#Scripts.Render("~/Scripts/tinymce/tinymce.min.js")
#Scripts.Render("~/Scripts/ckeditor/ckeditor.js")
#Scripts.Render("~/Scripts/site.js")
#Scripts.Render("~/Scripts/jquery.ui.datepicker-nl-BE.js")

Categories

Resources