Populate one DropDown List from another selected value - c#

I have two drop down list and I've populate them like this :
private List<Client> Client()
{
var allClients= _db.tboClient.Select(x =>
new Tecnico
{
Id = x.Id,
Nome = x.Nome
}).ToList();
return allClients;
}
private List<Pricerice> Price()
{
var allPrice = _db.tboPrice.Select(x =>
new Cliente
{
Id = x.Id,
Nome_azienda = x.Nome_azienda
}).ToList();
return allPrice ;
}
And then some methods that I recall Client() and Price(). I load the View like this :
public IActionResult Create()
{
ViewBag.Price= Pricei();
ViewBag.Clienti = CLienti();
return View();
}
This is the HTML:
<div class="dropdown">
#Html.DropDownListFor(m => m.CLienti, new SelectList(ViewBag.CLienti, "Id", "Nome_azienda"), new { #id = "ddlCLienti", #class = "btn btn-primary dropdown-toggle mr-3" })
</div>
<div class="dropdown">
#Html.DropDownListFor(m => m.Price, new SelectList(ViewBag.Price, "Id", "Nome"), new { #id = "ddlClienti", #class = "btn btn-primary dropdown-toggle mr-3" })
</div>
I want to populate the second(Price) drop down list based on the value selected from the first drop down list.

I want to populate the second(Price) drop down list based on the value selected from the first drop down list.
To achieve above requirement of implement a cascading dropdown, you can try to populate the second dropdown based on the previous selection of the first dropdown on "ddlCLienti" dorpdown change event, like below.
<script>
$(function () {
$("select#ddlCLienti").change(function () {
var CLienti = $(this).val();
$("select#ddlPrice").empty();
$.getJSON(`/your_controller_name_here/GetPriceBySelectedCLienti?CLienti=${CLienti}`, function (data) {
//console.log(data);
$.each(data, function (i, item) {
$("select#ddlPrice").append(`<option value="${item.id}">${item.nome}</option>`);
});
});
})
})
</script>
GetPriceBySelectedCLienti action method
public List<Price> GetPriceBySelectedCLienti(int CLienti)
{
//query data based on selected CLienti
//...

Related

How can I get textbox value based on Id in another table?

Why doesn't the textbox Name get value by Id?
So this is view ex_op:
This Id and Name, I get based on tbl_operator. When I entered Id then the Name will show.
This is controller ex_op:
public ActionResult Index()
{
var ex_op = db.ex_op.Include(e => e.tbl_exercises).Include(e => e.tbl_operator);
return View(ex_op.ToList());
}
public ActionResult Create()
{
ex_op exop = new ex_op();
var lasttest = db.ex_op.OrderBy(c => c.idTest).FirstOrDefault();
if (lasttest == null)
{
exop.idTest = "EXOP000";
}
else
{
exop.idTest = "EXOP" + (Convert.ToInt32(lasttest.idTest.Substring(6, lasttest.idTest.Length - 6)) + 1).ToString("D3");
}
ViewBag.idEx = new SelectList(db.tbl_exercises, "idEx","idEx");
ViewBag.idOp = new SelectList(db.tbl_operator, "idOp","idOp");
return View(exop);
}
And this is View ex_op
<div class="form-group">
<label class="control-label col-md-2">Name</label>
<div class="control-label col-md-10">
#Html.EditorFor(model => model.tbl_operator.nama, new { htmlAttributes = new { #class = "form-control", #readonly = "readonly" } })
#Html.ValidationMessageFor(model => model.tbl_operator.nama, "", new { #class = "text-danger" })
</div>
</div>
I don't know what I forget in this code, maybe i missing the code
please help me.
To auto fill the Name field once a ID Operator is selected you will need to use events to trigger a call to your Controller and return JSON then fill in the Field.
Client Side:
Checks for a change to the operator id dropdown and send a request to the server.
$('#OperatorId').change(function() {
var str = this.options[this.selectedIndex].value;
$.ajax('#Url.Action("GetOperatorName", "Home")', {
type: 'POST',
dataType: 'json',
data : {'operatorId': str }.
success: function(data, status, jqXHR) {
if ("success" === status) {
document.getElementById('#OperatorName').value = data.OperatorName;
} else {
alert('This Operator ID is not valid. Try again!');
}
}
});
});
Server-side:
Receives the ajax request looks up the operator and return the object
public async Task<JsonResult> GetOperatorName(string operatorId)
{
var item = await Operators.Get(x => x.Id == operatorId);
return Json(item);
}
You will need to change the fields and endpoint etc as needed, but this gives you the idea how to achieve what you need.

Refresh DropDownList Based on Value From Input Field

Is it possible to refresh a #Html.DropDownList based on value from an input field on the same form?
For example, I have a field #Html.TextBoxFor(m => m.CustomerFunds) to which a value such as 50 would be entered, as soon as the user exits the field such as TAB for example, a function would be initiated to populate the DropDownList.
HomeController.cs
public ViewResult Index()
{
var productList = new List<WebApplication1.Product>
{
new WebApplication1.Product{ProductName = "Please select a Product", ProductId = 0}
};
productList.AddRange(_repository.GetAllProducts());
ViewBag.ProductList = new SelectList(productList, "ProductId", "ProductName", null);
return View();
}
public SelectList GetProducts(int customerFunds)
{
var productList = new List<WebApplication1.Product>
{
new WebApplication1.Product {ProductName = "Please select a Product", ProductId = 0}
};
productList.AddRange(_repository.GetProducts(customerFunds));
return new SelectList(productList, "ProductId", "ProductName", null);
}
Index.cshtml
#using (Html.BeginForm("Index", "Home", FormMethod.Post, new { role = "form" }))
{
#Html.TextBoxFor(m => m.CustomerFunds)
#Html.DropDownList("ProductId", ViewBag.ProductList as SelectList)
}
Updated
I have changed the function GetProducts as follows:
public ActionResult GetProducts(decimal customerFunds)
{
var products = _repository.GetProducts(customerFunds).Select(p => new { p.ProductId, p.ProductName }).OrderBy(p => p.ProductName);
return Json(products, JsonRequestBehavior.AllowGet);
}
The Index.cshtml is now as follows:
#using (Html.BeginForm("Index", "Home", FormMethod.Post, new { role = "form" }))
{
#Html.TextBoxFor(m => m.CustomerFunds)
<select id="ProductId">
<option value="0">Please select a Product</option>
</select>
}
<script type="text/javascript">
$(document).ready(function () {
$('#ProductId').hide();
$('#CustomerFunds').blur(function () {
var customerFunds = $(this).val();
if (propertyValue.length > 0) {
$.getJSON('/Home/GetProducts', { customerFunds: customerFunds }, function (data) {
$('#ProductId').show();
$('#ProductId option').remove();
$('#ProductId').append('<option value="0">Please select a Product</option');
for (var i = 0; i < data.length; i++) {
$('#ProductId').append('<option value="' + data[i].ProductID + '">' + data[i].ProductName + '</option');
}
}).fail(function () {
debugger;
alert('Error getting Products');
});
}
else {
$('#ProductId option').remove();
$('#ProductId').append('<option value="0">Please select a Product</option');
}
});
});
</script>
Once data has been entered into CustomerFunds and the TAB key is pressed, the dropdown appears and is populated.
However, when viewing the source HTML of the page once the dropdown is populated, the actual select list only shows:
<select id="ProductId">
<option value="0">Please select a Product</option>
</select>
Despite the page actually rendering the list, the selected value of the dropdown is NOT passed into the model and therefor the Model Validation fails and I have no idea why.
Updated
Thanks to markpsmith the select for ProductId should be as follows:
<select id="ProductId" name="ProductId">
<option value="0">Please select a Product</option>
</select>

Populate textbox with related data from dropdownlist selected index

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

How to bind value to dropdownlist in asp.net mvc?

I have several textboxes and one dropdownlist like:
for (int i = 0; i < count; i++)
{
<tr>
<td>#Html.DropDownListFor(m => m.GetTimeSheetDetails[i].PROJ_ID, (SelectList)ViewBag.ProjectList, "-- Choose a Project --", new { #id = "ddlProjectvalue" })
</td>
<td>#Html.TextBoxFor(m => m.GetTimeSheetDetails[i].SUN_HRS, new { style = "width:50px; height:30px;", #class = "sunhrs" })
</td>
<td>#Html.TextBoxFor(m => m.GetTimeSheetDetails[i].MON_HRS, new { style = "width:50px; height:30px;", #class = "monhrs" })
</td>
<td>#Html.TextBoxFor(m => m.GetTimeSheetDetails[i].TUE_HRS, new { style = "width:50px; height:30px;", #class = "tuehrs" })
</td>
<td>#Html.TextBoxFor(m => m.GetTimeSheetDetails[i].WED_HRS, new { style = "width:50px; height:30px;", #class = "wedhrs" })
</td>
<td>#Html.TextBoxFor(m => m.GetTimeSheetDetails[i].THU_HRS, new { style = "width:50px; height:30px;", #class = "thurhrs" })
</td>
<td>#Html.TextBoxFor(m => m.GetTimeSheetDetails[i].FRI_HRS, new { style = "width:50px; height:30px;", #class = "frihrs" })
</td>
<td>#Html.TextBoxFor(m => m.GetTimeSheetDetails[i].SAT_HRS, new { style = "width:50px; height:30px;", #class = "sathrs" })
</td>
</tr>
</td>
}
and I want to bind data from database to all the fields , every thing is displaying data perfectly, but dropdown list for proj_id is not showing text even though i am passing value to dropdownlist. i am passing like :
public int GetTimsheetData(int empid, TimesheetModel TimesheetModel)
{
// GetimeSheet all the rows according employee name
var emps = (from n in db.TIMESHEETs
where n.RES_ID == empid
select n).ToList();
int count = emps.Count();
HttpContext.Current.Session["count"] = count;
try
{
List<TimesheetModel> emptyList = new List<TimesheetModel>();
TimesheetModel.GetTimeSheetDetails = emptyList; //taking Empty List and bind to GetTimesheetDetails for Add items into it.
//if Employee Name has more than one record.
if (emps.Count() > 0)
{
foreach (var timeSheet in emps)
{
TimesheetModel item = new TimesheetModel();
item.WEEK_CAL_ID = timeSheet.WEEK_CAL_ID;
item.PROJ_ID = timeSheet.PROJ_ID;
item.SUN_HRS = timeSheet.SUN_HRS;
item.MON_HRS = timeSheet.MON_HRS;
item.TUE_HRS = timeSheet.TUE_HRS;
item.WED_HRS = timeSheet.WED_HRS;
item.THU_HRS = timeSheet.THU_HRS;
item.FRI_HRS = timeSheet.FRI_HRS;
item.SAT_HRS = timeSheet.SAT_HRS;
TimesheetModel.GetTimeSheetDetails.Add(item);
}
}
}
catch (Exception ex)
{
throw ex;
}
return count;
}
and returning to controller like :
public ActionResult GetEmployeeDetails(int empId, string btn, TimesheetModel timesheetModel)
{
Employer_BL employerBL = new Employer_BL();
ViewBag.ProjectList = timesheetModel.getProjects;
//If GetTimesheetData returns morethan one record
if (employerBL.GetTimsheetData(empId, timesheetModel) >= 0)
{
timesheetModel.EMP_ID = empId;
//passes model data to View
return View("Timesheet", timesheetModel);
}
TimesheetModel model = new TimesheetModel();
model.EMP_ID = empId;
return View("Timesheet", model);
}
Where am I doing wrong, dropdownlist showing initial index instead of showing text of passing values. Please help me anyone.
in Separate Class I have written like below to get project names:
public SelectList getProjects()
{
IEnumerable<SelectListItem> projectslist = (from proj in res.PROJECTs where proj.IS_DELETED == "N" select proj).AsEnumerable().Select(projt => new SelectListItem() { Text = projt.NAME, Value = projt.ID.ToString() });
return new SelectList(projectslist, "Value", "Text", PROJ_ID);
}
It depends on the ViewBag.ProjectList which I cannot found on your source code. You could populate it with an object of type IEnumerable<SelectListItem> with one of the item Selected properties set to true.
public IEnumerable<SelectListItem> GetList()
{
return (from proj in res.PROJECTs where proj.IS_DELETED == "N" select proj).AsEnumerable().Select(projt => new SelectListItem() { Text = projt.NAME, Value = projt.ID.ToString() }).ToList();
}
on your controller
ViewBag.ProjectList = GetList();
on your view
#{
var projectList =
new SelectList(ViewBag.ProjectList, "Value", "Text", Model.GetTimeSheetDetails[i].PROJ_ID.ToString())
}
#Html.DropDownListFor(m => m.GetTimeSheetDetails[i].PROJ_ID, projectList, "-- Choose a Project --")
You can try like this method:
[NonAction]
private IEnumerable<SelectListItem> GetData()
{
return new List<SelectListItem>()
{
new SelectListItem(){ Text="--Select--", Value="0"},
new SelectListItem(){ Text="A", Value="1"},
new SelectListItem(){ Text="B", Value="2"},
new SelectListItem(){ Text="C", Value="3"},
};
}
Call this function in Action Method
public ActionResult Create()
{
ViewData["categories"] = GetData();
return View();
}
On your html page:
<%= Html.DropDownList("cat", (IEnumerable<SelectListItem>)ViewData["categories"])%>
You can use viewbag . in your controller you can read your data from the database :
public ActionResult Create()
{
ViewBag.ClassName = new SelectList(objclassrep.GetClasslist(), "Id", "ClassName");
}
And in your view model you can read the data from controller like this :
<div class="editor-label">
#Html.LabelFor(model => model.ClassId)
</div>
<div class="editor-field">
#Html.DropDownListFor(x => x.ClassId, (SelectList)ViewBag.ClassName);
#Html.ValidationMessageFor(model => model.ClassId)
</div>
This code automatically binds ids of your data to DDL Here is class id.
This is th getClassList function :
public List<Class> GetClasslist()
{
return _dbcontext.Classes.ToList();
}

How to change the value in Html.TextBox for using Jquery and Json?

In the create view what i am trying to do is when you choose a name from the dropdown list to fill the Login html.TextBoxFor automatically with his details.
Currently the Login textbox remains empty when i choose a person from dropdown list.
So i ve got my json object and tested as well my sql which is fine so i suppose the issue must be somewhere in jquery.
I would be glad if you could help me find the error.
View :
#using (Html.BeginForm()) {
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
<fieldset>
<legend>User</legend>
<div class="editor-label">#Html.LabelFor(model => model.UserLogin)</div>
<div class="editor-field">#Html.TextBoxFor(model => model.UserLogin, new {id ="LoginId" })
#Html.ValidationMessageFor(model => model.UserLogin)</div>
<div class="editor-label">#Html.LabelFor(model => model.UserFullName)</div>
<div class="editor-field">#Html.DropDownList("UserFullName", ViewBag.UserFullName as SelectList, "Select a User", new { id = "UserID" })
#Html.ValidationMessageFor(model => model.UserFullName)</div>
<p>
<input type="submit"
value="Create" />
</p>
</fieldset> }
<div>#Html.ActionLink("Back to List", "Index")</div>
<script type="text/javascript">
$('#UserID').on('change', function () {
$.ajax({
type: 'POST',
url: '#Url.Action("GetUserForm")',
data: { FullName: $('#UserID').val() },
success: function (results){
var login = $('#LoginId');
login.empty();
$.each(results, function ()
{
login.val(this.ID).text(this.Value);
});
}});
});
</script>
Controller:
public ActionResult Create()
{
var names = StaffDB.StaffData.AsEnumerable().Select(s => new
{
ID = s.ID,
FullName = string.Format("{0} {1}", s.Forename1, s.Surname)
}).ToList();
if(ModelState.IsValid)
{
db.Users.Add(user);
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.UserFullName = new SelectList(names, "FullName", "FullName", user.UserFullName);
return View(user);
}
[HttpPost]
public JsonResult GetUserForm(string FullName)
{
//pseudo code
var data = from s in StaffDB.StaffData
where s.Forename1 + ' ' + s.Surname == FullName
select new
{
Value = s.Login,
ID = s.ID
};
return Json(data);
}
I think the issue is while returning the json, In MVC by default Jsonresult is "Deny get", so you have add "Allow Get".
[HttpPost]
public JsonResult GetUserForm(string FullName)
{
//pseudo code
var data = from s in StaffDB.StaffData
where s.Forename1 + ' ' + s.Surname == FullName
select new { Value = s.Login, ID = s.ID };
if (data == null)
return Json(null);
return Json(data , JsonRequestBehavior.AllowGet);
}

Categories