Create click (2nd Partial view) is not hit into action controller. I have used two partial view. I tried the below steps. please see the attached screen shot
While clicking Add button (Index), Dropdown Selected value is added into partial view(1st partial view)
On Click Edit, another partial view(2nd) is loaded into div.
2'nd PV (Create) click, i'm planning to validate model(SubmitReview), generate xml and update to previous partial view, but this is not happening. please see the below code and suggest me how to achieve?
public ActionResult Index()
{
var DBQList = DBActivity.Getdbqlist();
DBQModel viewmodel = new DBQModel();
var DBQSelectList = new SelectList(DBQList, "DBQ_ID", "DBQ_Name", "IsSelected");
viewmodel.selectList = DBQSelectList;
Session["Session_DBQModel"] = viewmodel;
return View(viewmodel);
}
[HttpPost]
public ActionResult Index(DBQModel dbqModel)
{
if (ModelState.IsValid)
{
//
}
var mdl = (DBQModel)Session["Session_DBQModel"];
var selectedvalue = Convert.ToInt32(Request.Form["SelectedId"].ToString());
var rows = DBActivity.Getdbqlist().FirstOrDefault(x => x.DBQ_ID == selectedvalue);
if (rows != null)
{
DBQTable tbl = new DBQTable();
tbl.DBQ_ID = rows.DBQ_ID;
tbl.DBQ_Name = rows.DBQ_Name;
tbl.DBQ_Desc = rows.DBQ_Desc;
tbl.VAFormNo = rows.VAFormNo;
mdl.dbqTable.Add(tbl);
}
Session["Session_DBQModel"] = mdl;
return View(mdl);
}
public PartialViewResult LoadDBQ(int id)
{
if (id==1)
{
EatingDisorder eatingDisorder = new EatingDisorder();
return PartialView("_EatingDisorderPV", eatingDisorder);
}
return PartialView("_DefaultPV");
}
[HttpPost]
public ActionResult SubmitReview(EatingDisorder _model)
{
try
{
if (!ModelState.IsValid)
{
string messages = string.Join("; ", ModelState.Values
.SelectMany(x => x.Errors)
.Select(x => x.ErrorMessage));
throw new Exception("Please correct the following errors: " + Environment.NewLine + messages);
}
if (_model.s1_Bulima)
{
if ((_model.s1_Bulima_Date != null) && (string.IsNullOrEmpty(_model.s1_Bulima_ICD)) && (!string.IsNullOrEmpty(_model.s1_Bulima_Name)))
{
//ok
}
else
{
ModelState.AddModelError("s1_Bulima_Date", "s1_Bulima_Date is required.");
ModelState.AddModelError("s1_Bulima_ICD", "s1_Bulima_ICD is required.");
ModelState.AddModelError("s1_Bulima_Name", "s1_Bulima_Name is required.");
}
}
//save to db
//return Json(new { Result = "OK" });
}
catch (Exception ex)
{
//return Json(new { Result = "ERROR", Message = ex.Message });
ModelState.AddModelError("", ex.Message);
}
return PartialView("_EatingDisorderPV", _model);
}
Iindex.cshtml
#model WebApplication1.Models.DBQModel
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
#Html.DropDownListFor(n => n.SelectedId, Model.selectList, "Please select dbq", new { #class = "from-control col-md-4" })
<input type="submit" value="Add" class="btn btn-default" />
#Html.Partial("_DBQGridPV", Model.dbqTable)
<div id="DBQHolder"></div>
}
_DBQGridPV.cshtml
#model IEnumerable<WebApplication1.Models.DBQTable>
<table class="table">
<tr>
<th>#Html.DisplayNameFor(model => model.DBQ_ID)</th>
.....
<th></th>
</tr>
#foreach (var item in Model)
{
<tr>
<td>#Html.DisplayFor(modelItem => item.DBQ_ID)</td>
.....
<td>
#Ajax.ActionLink("Edit", "LoadDBQ", new { id = item.DBQ_ID },
new AjaxOptions { HttpMethod = "GET", UpdateTargetId = "DBQHolder", InsertionMode = InsertionMode.Replace })|
#Html.ActionLink("Delete", "DeleteDBQ", new { id = item.DBQ_ID })
</td>
</tr>
}
</table>
_EatingDisorderPV.cshtml
#model WebApplication1.Models.EatingDisorder
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
.....
<input type="submit" value="Create" />
}
Related
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>
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;
}
}
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);
}
NPG_Chemical_Measurement_Methods is an ICollection type. In my Chemical.cshtml, I have:
<div id="nioshs">
#Html.EditorFor(model => model.NPG_Chemical_Measurement_Methods)
</div>
and in the EditorTemplate view:
<div class="method" style="display:inline-block;">
<p>
#Html.RemoveLink("x", "div.method", "input.mark-for-delete")
#Html.HiddenFor(x => x.DeleteMethod, new { #class = "mark-for-delete" })
#Html.TextBoxFor(x => x.Measurement_Method)
#Html.ValidationMessageFor(model => model.Measurement_Method, "", new { #class = "text-danger" })
#Html.Hidden("Measurement_Type", "NIOSH")
</p>
</div>
I want to have something like when I give input for #Html.TextBoxFor(x => x.Measurement_Method), then click on other place of the current page, an alert will popup says Not exist in Database if record cannot be found in Measurement_Method table.
NPG_Chemical.cs has:
public partial class NPG_Chemical
{
public NPG_Chemical()
{
this.NPG_Chemical_Measurement_Methods = new HashSet<NPG_Chemical_Measurement_Method>();
}
[StringLength(256)]
[Remote("IsUserExists", "NPG_Chemical", ErrorMessage = "Chemical Name already in use")]
public string Chemical { get; set; }
public virtual ICollection<NPG_Chemical_Measurement_Method> NPG_Chemical_Measurement_Methods { get; set; }
internal void CreateMeasurementMethods(int count = 1)
{
for (int i = 0; i < count; i++)
{
NPG_Chemical_Measurement_Methods.Add(new NPG_Chemical_Measurement_Method());
}
}
Measurement_Method.cs has:
public partial class NPG_Chemical_Measurement_Method
{
[StringLength(256)]
[Remote("IsNIOSHExists", "NPG_Chemical", ErrorMessage = "NIOSH number does not exist")]
public string Measurement_Method { get; set; }
}
NPG_ChemicalController has:
public JsonResult IsUserExists(string Chemical)
{
return Json(!db.NPG_Chemical.Any(x => x.Chemical == Chemical), JsonRequestBehavior.AllowGet);
}
public JsonResult IsNIOSHExists(string Measurement_Method)
{
System.Diagnostics.Debug.WriteLine("value:",Measurement_Method);
return Json(db.NPG_NIOSH_Method.Any(x => x.Measurement_Number == Measurement_Method), JsonRequestBehavior.AllowGet);
}
This hopefully will get you close. I'm just writing this from memory. But basically one way to do this is handle an onblur event of your textbox with a javascript function. Then do an ajax call to a controller sending the value of Measurement_Method, validate the data and return true or false. If false show an alert box. You'll need to include the jquery library to use this.
#Html.TextBoxFor(x => x.Measurement_Method, new {onblur = "Validate()"})
Then javascript
function Validate() {
$.ajax({
url: "#Url.Action("CheckTextField", "Controller")\?value=" + $('#Measurement_Method').val(),
dataType: "html",
success: function(data) {
if (data == "false")
{
alert('Not exist in Database');
}); }
Your controller
public string CheckTextField(string value)
{
//validate the value here
return "true" or "false"
}
I am using jquery tab ui. My second tab contains this form when posted, does not refresh a partial view I have nested. What could be the problem?
_Partial_Item_Tab.cshtml
#model Mvc5.Models.ORDER_DETAILSMetadata
#{
var ordernumber = (int)Session["Order_Number"];
}
#using (Ajax.BeginForm("Items", "Order",
new AjaxOptions
{
HttpMethod = "POST",
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "target"
}))
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
#Html.TextBoxFor(model => model.id)
<input type="submit" value="Add" class="btn btn-default" />
}
<div id="target">
#Html.Action("Items_List", new { id = ordernumber }); <==== This does not show up after postback. Only after clicking browser refresh button does it show.
</div>
Items Controller (HttpPOST)
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Items(ORDER_DETAILSMetadata model)
{
// check to see if exists
//update order
Order order = new Order();
....
return PartialView("_Partial_Item_Tab", order);
}
Item_List Controller
public ActionResult Items_List(int id)
{
List<ORDER_DETAILS> result = db.ORDER_DETAILS.Where(p => p.Order_Number == id).ToList();
return PartialView("_Partial_Items_List", result);
}