I have filled the ViewBag.BankNames using Banks table as
ViewBag.BankNames = new SelectList(db.Banks, "BankId", "BankName", applicationSettings.BankId);
where applicationSettings.BankdId is having the value which I need to show as the selected value in dropdown, then passed the applicationSetting model object to view.
In my View I have used that ViewBag like
#Html.DropDownListFor(model => model.BankId, ViewBag.BankNames as SelectList, "Select Bank", htmlAttributes: new { #class = "form-control" })
It will show me the dropdown list with all values of Bank names but the selected value is Select Bank and not the value which I set as selected value in ViewBag?
Can you assign applicationSettings.BankId to BankId of model property and check..
you are binding #Html.DropDownListFor(model => model.BankId, ViewBag.BankNames as SelectList, "Select Bank", htmlAttributes: new { #class = "form-control" }) but in model.BankId is zero..
Assign Model.BankId = applicationSettings.BankId before returning it to view
In Controller
public ActionResult Index()
{
var banks = new List<Banks>()
{
new Banks()
{
BankId =1,
BankName = "Bank 1"
},
new Banks()
{
BankId =2,
BankName = "Bank 2"
}
};
var list = new SelectList(banks, "BankId", "BankName");
ViewBag.Banks = list;
var modelBanks= new Banks();
modelBanks.BankId = 2;
return View(modelBanks);
}
In View
#model Banks
#using WebApplication3.Models
#Html.DropDownListFor(model => model.BankId, ViewBag.Banks as SelectList,"Select Bank")
Related
I do already have dropdownlist in my ASP.NET MVC 5 project.
I need to remove one of the item parameter call it "Admin"; I want remove it from the list when the page is loaded.
This is my Razor markup:
<div class="form-group">
#Html.LabelFor(model => model.RoleName, htmlAttributes: new { #class = "control-label col-md-3" })
<div class="col-md-9">
#Html.DropDownListFor(model => model.RoleName, Model.VMRoles, new { #class = "form
control input-sm", multiple= "multiple" })
#Html.ValidationMessageFor(model => model.RoleName, "", new { #class = "text-danger" })
</div>
</div>
And this the C# controller:
[HttpGet]
[Authorize]
public ActionResult Create()
{
var vm = new CreateUserViewModel
{
VMSisterConcerns = _sisterConcernService.GetAllSisterConcern().Select(c => new SelectListItem { Text = c.Name, Value = c.ConcernID.ToString() }).ToList(),
VMRoles = _roleService.GetAllRole().Select(r => new SelectListItem { Text = r.Name, Value = r.Name }).ToList(),
ConcernId = User.Identity.GetConcernId().ToString()
};
return View(vm);
}
And this the model:
public ICollection<System.Web.Mvc.SelectListItem> VMRoles { get; set; }
Here is the correct answer thanks for #itsme86 he mention How to understand LINQ .
VMRoles = _roleService.GetAllRole().Where(r => r.name != "Admin").Select(r => new SelectListItem { Text = r.Name, Value = r.Name }).ToList(),
I work with ASP.NET MVC and I have an ODBC connection for database and have retrieved two drop down list from controller to view using queries.
Those two drop down lists are:
#Html.DropDownListFor(model => model.storageLocation, new SelectList(Model.locationGroupDD, "storageLocation", "storageLocation"), "Choose Location Group", new { #id = "storageLocation", #class = "dropdown1" })
#Html.DropDownListFor(model => model.storageLocationList, new SelectList(Model.locationDD,"storageLocationList","storageLocationList"), "Choose Location", new { #id = "storageLocationListDropDown", #class = "dropdown1" })
I'm new to JQuery and not sure how to script this. However, I found this script online and tried using the following to make necessary changes but I literally don't know how to modify/proceed. Any help is appreciated! Thank you.
Following are the queries I used to retrieve the data from database:
For drop downlist 1: select abc from xyz;
For drop downlist 2: select pqr from lmn where abc = "some value";
I want to pass the selected value from drop down list 1 to controller to execute query for second drop down list.
Please follow the following steps to make Cascading DropdownList in ASP.NET MVC:
1. In your Controller:
public class YourControlleNameController : Controller
{
public ActionResult Create()
{
var LocationGroupDDList = _dbContext.LocationGroupDD.Select(lgdd =>
new { lgdd.LocationGroupDDId, lgdd.LocationGroupDDName }).ToList();
ViewBag.LocationGroupDDSelectList = new SelectList(LocationGroupDDList, "LocationGroupDDId", "LocationGroupDDName");
ViewBag.LocationDDListSelectList = new SelectList(new List<LocationDD>(), "LocationDDId", "LocationDDName");
return View();
}
[HttpPost]
public ActionResult Create(YourModel model, string LocationGroupDDId)
{
if (ModelState.IsValid)
{
// Do necessary staff here
}
var LocationGroupDDList = _dbContext.LocationGroupDD.Select(lgdd =>
new { lgdd.LocationGroupDDId, lgdd.LocationGroupDDName }).ToList();
ViewBag.LocationGroupDDSelectList = new SelectList(LocationGroupDDList, "LocationGroupDDId", "LocationGroupDDName",LocationGroupDDId);
var LocationDDList = _dbContext.LocationDD.Where(ldd => ldd.LocationGroupDDId == LocationGroupDDId).Select(ldd => new {ldd.LocationDDId, ldd.LocationDDName}).ToList();
ViewBag.LocationDDListSelectList = new SelectList(LocationDDList, "LocationDDId", "LocationDDName",model.LocationDDId);
return View();
}
public JsonResult GetLocationDDByLocationGroupDD(string LocationGroupDDId)
{
var LocationDDList = _dbContext.LocationDD.Where(ldd => ldd.LocationGroupDDId == LocationGroupDDId)
.Select(ldd => new {ldd.LocationDDId, ldd.LocationDDName}).ToList();
return Json(LocationDDList, JsonRequestBehavior.AllowGet);
}
}
2. In the View:
<div class="form-group">
#Html.Label("LocationGroupDD", "Location GroupDD Name", htmlAttributes: new { #class = "control-label" })
#Html.DropDownList("LocationGroupDDId", ViewBag.LocationGroupDDSelectList as SelectList, "Select Location GroupDD", htmlAttributes: new { #class = "form-control", #id = "LocationGroupDD" })
</div>
<div class="form-group">
#Html.Label("LocationDD", "LocationDD Name", htmlAttributes: new { #class = "control-label" })
#Html.DropDownList("LocationDDId", ViewBag.LocationDDListSelectList as SelectList, "Select LocationDD", htmlAttributes: new { #class = "form-control", #disabled = "disabled", #id = "LocationDD" })
</div>
3. jQuery in the view:
#section Scripts {
<script type="text/javascript">
$(document).on('change','#LocationGroupDD', function(){
var LocationGroupDDId = $(this).val();
$('#LocationDD').empty();
if (LocationGroupDDId) {
$.ajax({
type: "GET",
url: '#Url.Action("GetLocationDDByLocationGroupDD", "YourControlleName")',
data: { LocationGroupDDId: LocationGroupDDId},
success: function(data) {
if (data.length > 0) {
$('#LocationDD').prop("disabled", false);
$('#LocationDD').append($("<option>").val("").text("Select LocationDD"));
$(data).each(function(index, item) {
$('#LocationDD').append($("<option>").val(item.LocationDDId).text(item.LocationDDName));
});
} else {
$('#LocationDD').append($("<option>").val("").text("LocationDD List Is Empty"));
}
}
});
} else {
$('#LocationDD').prop("disabled", true);
$('#LocationDD').append($("<option>").val("").text("Select Location GroupDD First"));
}
});
</script>
}
Hope this will solve your problem!
I'm new in ASP.NET MVC and i have a problem. I needed to get a string "Category" from a dropdownlist, that was my code:
var CList = new List<string>();
StreetFooder sf = db.StreetFooders.Single(s => s.User.UserName == this.User.Identity.Name);
var Cqry = from d in db.Categories
where !d.IsDeleted && d.StreetFooder.Id == sf.Id
orderby d.Name
select d.Name;
CList.AddRange(Cqry.Distinct());
ViewBag.CategoryList = new SelectList(CList);
And the view:
<div class="col-md-10">
#Html.DropDownListFor(model => model.Category, (SelectList)ViewBag.CategoryList, new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.Category, "", new { #class = "text-danger" })
</div>
And that worked for me. After that, i realized i made a mistake and changed my string Category attribute in:
public virtual Categories Type { get; set; }
Now i want to save on my db the ID instead of string, but still want to see my string when select from dropdown list...but don't know how.
Use SelectListItem to create the SelectList, there you can specify Value = your id and Text = display text
https://msdn.microsoft.com/en-us/library/system.web.mvc.selectlistitem(v=vs.118).aspx
var CList = new List<SelectListItem>();
StreetFooder sf = db.StreetFooders.Single(s => s.User.UserName == this.User.Identity.Name);
var Cqry = from d in db.Categories
where !d.IsDeleted && d.StreetFooder.Id == sf.Id
orderby d.Name
select d;
CList.AddRange(Cqry.Distinct().Select(x => new SelectListItem
{
Value = x.Id.ToString(),
Text = d.Name
}));
ViewBag.CategoryList = new SelectList(CList);
You can even omit using the SelectList and simply pass a List<SelectListItem> if I recall correctly.
Try this:
var cqry = from d in db.Categories
where !d.IsDeleted && d.StreetFooder.Id == sf.Id
orderby d.Name
select new { Id = d.StreetFooder.Id, Value = d.Name};
ViewBag.CategoryList = new SelectList(cqry.Distinct(), "Id", "Value");
You need to also define Id and pass it to your DropDownList. This will initialize a new instance of the SelectList class by using the specified items for the list(cquery), the data value field(Id), and the data text field(Value) and add to you ViewBag then bind it to DropDownList.
You can use it on View like this:
#Html.DropDownList("CategoryList ", null, new { #class = "form-control" })
cqry.Distinct() will work if you have duplicates on result, which means that the Id and Value in collection are same, if you need to distinct only by name, you need to use group by.
In selectList, you can pass from which property you want to bind dropdown value and text property.
var Cqry = from d in db.Categories
where !d.IsDeleted && d.StreetFooder.Id == sf.Id
group d by new { names.Name } into nameGroup
select new { Name = nameGroup.Name, Id = nameGroup.FirstOrDefault().StreetFooder.Id};
ViewBag.CategoryList = new SelectList(Cqry,"Id","Name");
You were selecting Distinct name, so I have used here group by name.
As I've created anonymous object with property 'Id' and Name. Now you can bind it in SelectList.
This question already has an answer here:
How to keep cascade dropdownlist selected items after form submit?
(1 answer)
Closed 5 years ago.
I'm using MVC , C# and Entity Framework.
The object on my model are:
State-------- Id , Name
City ------- Id , Name , StateId
TheObject----Id, Name, StateId, CityId
I want to create an edit form for TheObject.
The Edit form has 2 dropdownlist State and City that are created dynamically , and the City list depend on selection made on State List.
The problem is that the dropdown list are filled correctly , but when the edit form is open these 2 dropdownlist are in empty state and does not have selected the real values for the object that is edited .
The partial code for Edit view is this :
<div class="form-group">
#Html.LabelFor(u => u.State, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(u => u.State,
new SelectList(ViewBag.State, "Id", "Name"),
"Choose State",
new { #class = "form-control", #onchange = "selectCities()" })
#Html.ValidationMessageFor(u => u.State, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(u => u.City, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(u => u.City,
new SelectList(Enumerable.Empty<SelectListItem>(), "Id", "Name"),
"Choose City",
new { #class = "form-control" })
#Html.ValidationMessageFor(u => u.City, "", new { #class = "text-danger" })
</div>
</div>
function selectCities() {
debugger;
var stateId = $("#State").val();
$.ajax({
url: '/Home/selectCities',
type: 'POST',
datatype: 'application/json',
contentType: 'application/json',
data: JSON.stringify({ stateId: +stateId }),
success: function (result) {
$("#City").html("");
$("#City").append
($('<option></option>').val(null).html("---choose City---"));
$.each($.parseJSON(result), function (i, cty)
{ $("#City").append($('<option></option>').val(cty.Id).html(cty.Name)) })
},
error: function () { alert("Error !") },
});
}
The partial code of the controller is this :
private void Fill_StateDropDownList()
{
var st = from d in db.States
orderby d.Name
select d;
ViewBag.State = st.ToList();
}
[HttpPost]
public ActionResult selectCities(string stId)
{
List < City > lstcity = new List < City > ();
int stateiD = Convert.ToInt32(stId);
lstgrupet = (from d in db.Citys
where d.StateID==stateiD
select d).ToList();
string result= JsonConvert.SerializeObject(lstgrupet, Formatting.Indented,
new JsonSerializerSettings { ReferenceLoopHandling = ReferenceLoopHandling.Ignore});
return Json(result, JsonRequestBehavior.AllowGet);
}
public ActionResult Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
TheObject obj = db.TheObjects.Find(id);
if (obj == null)
{
return HttpNotFound();
}
Fill_StateDropDownList()
return View(obj);
}
[HttpPost, ActionName("Edit")]
[ValidateAntiForgeryToken]
public ActionResult EditPost(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
var theobjectToUpdate = db.TheObjects.Find(id);
if (TryUpdateModel(theobjectToUpdate, "",
new string[] { "Name","StateId","CityId" }))
{
try
{
db.SaveChanges();
return RedirectToAction("Index");
}
catch (Exception)
{
ModelState.AddModelError("", "Error.");
}
}
Fill_StateDropDownList()
return View(theobjectToUpdate);
}
actually SelectList has a construct with a parameter called selectedValue
now you should know how to do it
in edit View
<div class="form-group">
#Html.LabelFor(u => u.State, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(u => u.State,
new SelectList(ViewBag.State, "Id", "Name", Model.State),
"Choose State",
new { #class = "form-control", #onchange = "selectCities()" })
#Html.ValidationMessageFor(u => u.State, "", new { #class = "text-danger" })
</div>
</div>
You already have the saved state and city values. All you have to do is to load the subset of cities based on the saved state id and use that collection to render the dropdown for cities
The DropDownListFor helper method will select the corresponding option from the SELECT element as long as the view model's City property value matches with one of the option's value attribute value.
public ActionResult Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
TheObject obj = db.TheObjects.Find(id);
if (user == null)
{
return HttpNotFound();
}
Fill_StateDropDownList()
FillCities(obj.State);
return View(obj);
}
private void FillCities(int stateId)
{
ViewBag.CityList = db.Cities
.Where(g => g.StateId== stateId)
.Select(f => new SelectListItem() {
Value = f.Id.ToString(),
Text = f.Name })
.ToList();
}
Make an adjustment to the view
var cityList = new List<SelectListItem>();
if (ViewBag.CityList != null)
{
cityList =ViewBag.CityList as List<SelectListItem>;
}
#Html.DropDownListFor(u => u.City, cityList , "Choose City")
Another option is to make an ajax call on the page load (document ready to get the cities based on the value of state dropdown). It gets complicated if you have multiple nested dropdowns.(ends up in callback hell)
I would like to change two textboxes when I select option from dropdown but I don't know how can I do it.
I'm using dbml file for connecting to other database. I would like to use 2 properties for 2 textboxes = STOK_FIYAT and STOK_KODU.
private BETASYSEntities db = new BETASYSEntities();
private NETSISDataContext netsisdb = new NETSISDataContext();
public ActionResult Olustur(int FormulID)
{
FormulasyonAyrintilari formulasyonayrintilari = new FormulasyonAyrintilari();
formulasyonayrintilari.FormulID = FormulID;
ViewBag.StokAdi = new SelectList(netsisdb.TBLSTSABIT, "STOK_ADI", "STOK_ADI");
return PartialView("_Olustur", formulasyonayrintilari);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Olustur([Bind(Include = "FormulAyrintilariID,FormulID,StokAdi,StokKodu,StokBirim,StokMiktar,StokFiyat")] FormulasyonAyrintilari formulasyonayrintilari)
{
if (ModelState.IsValid)
{
db.FormulasyonAyrintilari.Add(formulasyonayrintilari);
db.SaveChanges();
string url = Url.Action("Index", "FormulasyonAyrintilari", new { id = formulasyonayrintilari.FormulID });
return Json(new { success = true, url = url });
}
ViewBag.StokAdi = new SelectList(netsisdb.TBLSTSABIT, "STOK_ADI", "STOK_KODU", formulasyonayrintilari.StokAdi);
return PartialView("_Olustur", formulasyonayrintilari);
}
#Html.DropDownList("StokAdi", null, "Lütfen Seçin", htmlAttributes: new { #class = "form-control col-md-3 select2", autocomplete = "off" })
#Html.EditorFor(model => model.StokKodu, new { htmlAttributes = new { #class = "form-control", autocomplete = "off" } })
#Html.EditorFor(model => model.StokFiyat, new { htmlAttributes = new { #class = "form-control", autocomplete = "off" } })
Create an action that returns JsonResult which will receive the value STOK_ADI and returns a JSON Object that has STOK_KODU and STOK_FIYAT
public JsonResult GetValuesForSTOK_ADI(string STOK_ADI)
{
//get the values from the DB for the provided STOK_ADI
return Json(new {STOK_KODU ="value from db",STOK_FIYAT="value from db"},JsonRequestBehavior.AllowGet));
}
In your view, change the declaration for the drop down to add an onchange event that will call the action
#Html.DropDownList("StokAdi", null, "Lütfen Seçin", htmlAttributes: new { #class = "form-control col-md-3 select2", autocomplete = "off",onchange="updateTextBoxes()"})
at the end of the file, create the below javascript function
<script>
function updateTextBoxes()
{
var selectedSTOK_ADI = $("#StokAdi").val();
$.ajax('#Url.Action("GetValuesForSTOK_ADI","ControllerName")').then(function(data){
$("#StokKodu").val(data.STOK_KODU);
$("#StokFiyat").val(data.STOK_FIYAT);
});
}
</script>