Refresh DropDownList Based on Value From Input Field - c#

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>

Related

Populate one DropDown List from another selected value

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
//...

C# Mvc Web Api Cascading List

This is my controller.
public class DokuzasController : Controller
{
public ActionResult AddOrEdit()
{
DersViewModel model = new DersViewModel();
schoolEntities sc = new schoolEntities();
List<ders> dersList = sc.ders.OrderBy(f => f.Ders1).ToList();
model.DersList = (from s in dersList
select new SelectListItem
{
Text = s.Ders1,
Value = s.DersID.ToString()
}).ToList();
model.DersList.Insert(0, new SelectListItem { Value = "", Text = "Select"});
return View(model);
}
[HttpPost]
public ActionResult AddOrEdit(DersViewModel model)
{
if (model.LectureId == 0)
{
HttpResponseMessage response = GlobalVariables.LecturesClient.PostAsJsonAsync("dokuzas", model).Result;
TempData["SuccessMessage"] = "Saved.";
}
else
{
HttpResponseMessage response = GlobalVariables.LecturesClient.PutAsJsonAsync("dokuzas/" + model.LectureId, model).Result;
TempData["SuccessMessage"] = "Successful.";
}
return RedirectToAction("Index");
}
[HttpPost]
public JsonResult SaatList(int id)
{
schoolEntities sc = new schoolEntities();
List<saat> saatList = sc.saat.Where(f => f.DersID == id).OrderBy(f => f.Saat1).ToList();
List<SelectListItem> itemList = (from i in saatList
select
new SelectListItem
{
Value = i.SaatID.ToString(),
Text = i.Saat1
}).ToList();
return Json(itemList, JsonRequestBehavior.AllowGet);
}
}
And this is my AddOrEdit file.
#model Mvc.Models.DersViewModel
#{
ViewBag.Title = "AddOrEdit";
}
#using (Html.BeginForm("AddOrEdit", "Dokuzas", FormMethod.Post))
{
#Html.DropDownListFor(m => m.DersID, Model.DersList)
<br /><br />
#Html.DropDownListFor(m => m.SaatID, Model.SaatList)
<br />
<input type="submit" value="Kaydet" class="btn button" />
}
#section scripts{
<script type="text/javascript">
$(document).ready(function () {
$("#DersID").change(function () {
var id = $(this).val();
var saatList = $("#SaatID");
saatList.empty();
$.ajax({
url: '/Dokuzas/SaatList',
type: 'POST',
dataType: 'json',
data: { 'id': id },
success: function (data) {
$.each(data, function (index, option) {
saatList.append('<option value=' + option.Value + '>'
+ option.Text + '</option>')
});
}
});
});
});
</script>
}
I have a table and this table contains Dersadi and Dagilimi properties. I wanted to create a cascading list and add to table from this list from DersList to Dersadi and from SaatList to Dagilimi. But i choose items and select submit button i can submit it but it added null to the table. It did not add what i choose from the list. How can i fix this?
in the view, you can use the DropDownList helper method to render the SELECT element with the data we set to the Model.DersList. We will also add our second dropdown as well.
#using (Html.BeginForm("AddOrEdit", "Dokuzas", FormMethod.Post))
{
#Html.DropDownList("DersID", Model.DersList as SelectList)
<select name="id" id="SaatID" data-url="#Url.Action("SaatList","Home")">
<br />
<input type="submit" value="Kaydet" class="btn button" />
}
<script type="text/javascript">
$(function(){
$("#DersID").change(function (e) {
var $SaatID = $("#SaatID");
var url = $SaatID.data("url")+'?id='+$(this).val();
$.getJSON(url, function (items) {
$.each(items, function (a, b) {
$vacancy.append('<option value="' + b.Value + '">' + b.Text + '</option>');
});
});
});
});
</script>

drop down list refresh in razor

I have a drop down list which represent states and according to selected state, I need to refresh City drop down list which represent the cities in the selected state. How can I refresh the city drop down ?
Here is my code :
public class AccountController : Controller
{
public static List<SelectListItem> StateListItem()
{
var stateList = new List<SeraydarBL.Accounts.State>();
var selectListItems = new List<SelectListItem>();
stateList = SeraydarBL.Accounts.SelectStates();
foreach (var state in stateList)
{
var selectListItem = new SelectListItem();
selectListItem.Text = state.name;
selectListItem.Value = state.id.ToString();
selectListItems.Add(selectListItem);
}
return selectListItems;
}
}
here is the razor :
#using (Html.BeginForm())
{
<fieldset>
<legend>Registration Form</legend>
<ol>
<li>
//-------------------------------------------------------
var stateList = new List<SelectListItem>();
stateList = AccountController.StateListItem();
}
#Html.LabelFor(model => model.StateId)
#Html.DropDownListFor(model => model.StateId, stateList, " Select your State ...")
#Html.ValidationMessageFor(m => m.StateId)
#*HERE MUST BE THE DROP DOWN LIST OF CITIES*#
</li>
</ol>
<input type="submit" value="Register" />
</fieldset>
<script>
$('#StateId').change(function () {
});
</script>
}
You can achieve this using jquery ajax call.
<script type="text/javascript">
$(document).ready(function () {
//Dropdownlist Selectedchange event
$("#StateId").change(function () {
$("#CityId").empty();
$.ajax({
type: 'POST',
url: '#Url.Action("GetCity")',
dataType: 'json',
data: { id: $("#StateId").val() },
success: function (cities) {
$.each(cities, function (i, city) {
$("#CityId").append('<option value="' + city.Value + '">' +``});
},
error: function (ex) {
alert('Failed to retrieve states.' + ex);
}
});
return false;
})
});
</script>
refer few articles
http://www.codeproject.com/Articles/730953/Cascading-Dropdown-List-With-MVC-LINQ-to-SQL-and-A
http://www.c-sharpcorner.com/UploadFile/4d9083/creating-simple-cascading-dropdownlist-in-mvc-4-using-razor/

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);
}

How get value from cascading drop down list made with ajax

I am very new to MVC, and am try to set up a series of cascading drop down lists using this example.
But I am stuck a little bit, because I don't know how to get the value from the second drop down and send it to controller when I press the appropriate button.
Here is my view:
<script type="text/javascript">
$('#list').change(function() {
var selectedClient = $(this).val();
if (selectedClient != null && selectedClient != '') {
$.getJSON('#Url.Action("SelectC")', { clientID: selectedClient }, function (client) {
var campaingSelect = $('#clist');
campaingSelect.empty();
$.each(client, function(index, clients) {
campaingSelect.append($('<option/>', {
value: clients.value,
text: clients.text
}));
});
});
}
});
</script>
#using (Html.BeginForm("CreateNewCampaign", "Home", FormMethod.Post))
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
#Html.LabelFor(m => m.alreadyCreatedCampaignName, "Name:")
#Html.DropDownList("clist","-- Select Client -2-")
<input type="Submit" name="button" value="Select" class="btn btn-primary" />
}
Controller:
public ActionResult SelectC(int clientId, CampaignModel model, FormCollection form)
{
Session["ClientID"] = clientId;
ViewBag.ClientName = "You're using: " + Session["ClientName"];
var CampaignInf = CampaignManagementService.GetCampaigns((string) Session["ticket"], clientId);
List<AlreadyCreatedCampaignList> itemas = new List<AlreadyCreatedCampaignList>();
foreach (var element in CampaignInf)
{
itemas.Add(new AlreadyCreatedCampaignList() {CampId = element.Key, CampName = element.Value});
}
var listOfCam = new SelectList(itemas, "campID", "campName", 1);
return Json(listOfCam.Select(x => new {value = x.Value, text = x.Text}), JsonRequestBehavior.AllowGet);
}
I want to get the value to other controller, and I am not sure of the right way to go about doing this.
You can get value of dropdownlist just by giving it ID and call $("#id").val();, then you can transfer it to the controller through ajax maybe.
Here is mine, try it
public ActionResult ActionName(string dropdown_value){
//your code
}
<script>
$(document).ready(function(){
$("submit").click(function(){
$.ajax({
url:"Controller/ActionName",
datatype: "POST",
data: { dropdown_value : $("#clist").val() },
success : function(){ //your code if success }
});
});
});
</script>

Categories