how to populate text boxes based on dropdownlist selection mvc - c#

I'm new to MVC, and very new to JQuery. I'm attempting to populate textboxes based on a dropdownlist selection. My Product model contains the fields ProductId, Name, and Price. I want to populate the ProductId and Price fields in my QuoteDetails based upon the product Name chosen. My controller action is as follows:
public ActionResult AddProduct(int quoteId, int quoteDetailId)
{
var items = db.Products.ToList();
ViewBag.ProductData = items;
ViewData["QuoteId"] = quoteId;
ViewData["QuoteDetailId"] = quoteDetailId;
return PartialView("EditQuoteDetail", new QuoteDetail { QuoteId = quoteId, QuoteDetailId = quoteDetailId, ProductId = 1, ProductName = " ", Amount = 1, ListPrice = 0, Discount = 0, Price = 0 });
}
The relevant portion of the partial view EditQuoteDetail is as follows:
#Html.HiddenFor(model => model.QuoteId, new { htmlAttributes = new { #class = "form-control" } })
#Html.HiddenFor(model => model.QuoteDetailId, new { htmlAttributes = new { #class = "form-control" } })
#Html.EditorFor(model => model.ProductId, new { htmlAttributes = new { #id="ProductId", #class = "form-control" } })
#Html.DropDownList("ProductName", new SelectList(ViewBag.ProductData, "Name", "Name"), new { #id = "ProductName" })
#Html.EditorFor(model => model.Amount, new { htmlAttributes = new { #class = "form-control" } })
#Html.EditorFor(model => model.ListPrice, new { htmlAttributes = new { #id="Price", #class = "form-control" } })
#Html.EditorFor(model => model.Discount, new { htmlAttributes = new { #class = "form-control" } })
#Html.EditorFor(model => model.Price, new { htmlAttributes = new { #class = "form-control" } })
The script I am using to attempt to populate the ProductId and Price fields is as follows:
<script type="text/javascript">
$(document).ready(function () {
$('#ProductName').change(function () {
$('#ProductId').val($(this).val());
$('#Price').val($(this).val());
});
});
</script>
But when I make the dropdown list selection, nothing happens. What am I doing wrong? Any help would be much appreciated.

Here's what I think is happening...
(1) #Html.DropDownList("ProductName", new SelectList(ViewBag.ProductData, "Name", "Name"), new { #id = "ProductName" })
This line creates a <select> html element with an id of "ProductName" as expected; though the value of the options within that list are text values. Because you are using the "Name" for both the value and text of the option. For example:
<select id="ProductName" name="ProductName">
<option value="Product 1">Product 1</option>
<option value="Product 2">Product 2</option>
</select>
(2) #Html.EditorFor(model => model.ProductId, new { htmlAttributes = new { #id="ProductId", #class = "form-control" } })
Since you are using the EditorFor Html helper, it is trying to validate an integer (I assume) of the ProductId. Your javascript is trying to insert a String, like "Product 1".
(3) #Html.EditorFor(model => model.ListPrice, new { htmlAttributes = new { #id="Price", #class = "form-control" } })
This has a slightly different issue. The ID of the HTML element will default to "ListPrice" and not be overridden by your #id property in the htmlAttributes object. Side question, do you mean to put #id = "Price" on the "ListPrice" element? Even if you fixup the ID attributes of these elements, you may still run into the data type issue from (2) above.
Try switching the target element to a TextBoxFor as a quick test.

The problem is not in the script you are populating dropdown
ViewBag.ProductData, "Name", "Name" by Name so the id of the dropdown will also be its Name and also ProductId and Price both are int so you cannot set text value in int field
So you should set the ViewBag.ProductData, "Id", "Name" when ever you will run the script it will get the int value of productId
Edit
if you want to get the data based on your Product id you have to make ajax call for that in jquery and you have to make action for that in controller
[HttpPost]
public ActionResult GetProduct(int pId)
{
var data = db.Products.Find(id);
return Json(data);
}
and your view would be
#model CMSUsersAndRoles.Models.QuoteDetail
#{
ViewBag.Title = "EditQuoteDetail";
Layout = null;
}
#{
var quoteId = (int)ViewData["QuoteId"];
var quoteDetailId = (int)ViewData["QuoteDetailId"];
}
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
</head>
<body>
<div id="row">
<table>
#using (Html.BeginCollectionItem("quoteDetail"))
{
<tr>
#Html.HiddenFor(model => model.QuoteId, new { htmlAttributes = new { #class = "form-control" } })
#Html.HiddenFor(model => model.QuoteDetailId, new { htmlAttributes = new { #class = "form-control" } })
#Html.TextBoxFor(model => model.ProductId, new { htmlAttributes = new { #id="ProductId", #class = "form-control" } })
#Html.DropDownList("ProductList", new SelectList(ViewBag.ProductData, "ProductId", "Name"), new { #id = "ProductList" })
#Html.EditorFor(model => model.Amount, new { htmlAttributes = new { #class = "form-control" } })
#Html.TextBoxFor(model => model.Price, new { htmlAttributes = new { #id="Price", #class = "form-control" } }
#Html.EditorFor(model => model.Discount, new { htmlAttributes = new { #class = "form-control" } })
#Html.EditorFor(model => model.ListPrice, new { htmlAttributes = new { #class = "form-control" } })
#Ajax.ActionLink(" ", "DeleteProduct", "QuoteViewModel", new { quoteId = Model.QuoteId, quoteDetailId = (Model.QuoteDetailId) },
new AjaxOptions
{
HttpMethod = "POST",
Confirm = "Are you Sure You Want to Delete " + Model.ProductName,
OnSuccess = "RemoveRow"
},
new { #class = "btn btn-danger glyphicon glyphicon-trash" })
</tr>
}
</table>
</div>
<script type="text/javascript">
$(document).ready(function () {
$('#ProductList').change(function () {
$.post("/QuoteViewModel/GetProduct", { pId: $(this).val() }, function (data) {
$('#ProductId').val(data.ProductId);
$('#Price').val(data.Price);
});
});
});
</script>
</body>
</html>

At last, I found an answer. travis.js started me on the right path when he said the BeginCollectionItem helper was overtaking my HTML, so I had to use id contains syntax to make it work. The working jQuery (in the parent view) is as follows:
<script type="text/javascript">
$(document).ready(function () {
$(document).on("change", '[id*="ProductList"]', function () {
$.post("/QuoteViewModel/GetProduct", { pId: $(this).val() }, function (data) {
$("[id*='ProductId']").val(data.ProductId);
$("[id*='Price']").val(data.Price);
});
});
});
</script>
And the controller action (thanks Usman) is as follows:
[HttpPost]
public ActionResult GetProduct(int pId)
{
var data = db.Products.Find(pId);
return Json(data);
}
Whew!

Related

Remove item from dropdownlist ASP.NET MVC 5 and C#

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(),

Session Datatable to database

Hello I am trying something in which I am not really an expert and only have reached so far with great help.
I have a table and a form such as this
!https://imgur.com/a/MIb112p
the table is populated by a datatable i stored in a session while the form is goes to a [httppost] method. my problem is when i click the save button the form data is being saved but not the table
my view looks like this
#using cgs.Models;
#model ConfirmOrderCustomModel
#using System.Data;
#using System.Net;
#{
ViewBag.Title = "EditProduct";
Layout = "~/Views/Shared/DashboardLayout.cshtml";
}
<div id="form-wrapper" class="page-wrapper">
<div id="overview-row" class="row">
<div class="col-lg-12">
<h1 class="page-header">Confirm Order</h1>
</div>
</div>
<div id="form-div" class="row edit-form">
#using (Html.BeginForm("ConfirmOrder", "Product", FormMethod.Post))
{
#Html.AntiForgeryToken()
#*#Html.ValidationSummary(false, "", new { #class = "text-danger" })*#
<div class="row">
<div class="col-lg-8">
<table id="calculate-table" class="rwd-table">
<tr>
<th>ID</th>
<th>Order Units</th>
<th>Total</th>
<th>Discount</th>
<th>Net</th>
</tr>
#{
if (Session["tblCart"] != null)
{
DataTable dt = (DataTable)Session["tblCart"];
foreach (DataRow row in dt.Rows)
{
<tr>
#foreach (DataColumn col in dt.Columns)
{
<td>#row[col.ColumnName]</td>
}
<td><input type="button" value="Remove" onclick="Remove(this)" /></td>
</tr>
}
}
}
</table>
</div>
</div>
<div class="row">
<div class="col-lg-8">
#Html.LabelFor(model => model.Orders.ShippingDate, new { htmlAttributes = new { #placeholder = "Shipping Date", #id = "lblShippingDate", #class = "label" } })
#Html.EditorFor(model => model.Orders.ShippingDate, new { htmlAttributes = new { #type = "date", #min = 0, #value = "", #placeholder = "Shipping Date", #name = "shippingDate", #id = "shippingDate", #required = "" } })
#Html.ValidationMessageFor(model => model.Orders.ShippingDate, "", new { #class = "text-danger" })
</div>
</div>
<div class="row">
<div class="col-lg-8">
#Html.LabelFor(model => model.Orders.OrderTotal, new { htmlAttributes = new { #placeholder = "Total", #id = "lblTotal", #class = "label" } })
#Html.EditorFor(model => model.Orders.OrderTotal, new { htmlAttributes = new { #type = "text", #min = 0, #value = "", #placeholder = "Total", #name = "total_price", #id = "total_price", #required = "" } })
#Html.ValidationMessageFor(model => model.Orders.OrderTotal, "", new { #class = "text-danger" })
</div>
</div>
<div class="row">
<div class="col-lg-8">
#Html.LabelFor(model => model.Orders.CustomerName, new { htmlAttributes = new { #placeholder = "Customer", #id = "lblCustomer", #class = "label" } })
#Html.EditorFor(model => model.Orders.CustomerName, new { htmlAttributes = new { #type = "text", #min = 0, #value = "", #placeholder = "Customer", #name = "cust_name", #id = "cust_name", #required = "" } })
#Html.ValidationMessageFor(model => model.Orders.CustomerName, "", new { #class = "text-danger" })
</div>
</div>
<div class="row">
<div class="col-lg-8">
#Html.LabelFor(model => model.Orders.CustomerPhone, new { htmlAttributes = new { #placeholder = "CustomerPhone", #id = "lblPhone", #class = "label" } })
#Html.EditorFor(model => model.Orders.CustomerPhone, new { htmlAttributes = new { #type = "text", #min = 0, #value = "", #placeholder = "Customer Phone", #name = "cust_phone", #id = "cust_phone", #required = "" } })
#Html.ValidationMessageFor(model => model.Orders.CustomerPhone, "", new { #class = "text-danger" })
</div>
</div>
<div class="row">
<div class="col-lg-8">
#Html.LabelFor(model => model.Orders.CustomerEmail, new { htmlAttributes = new { #placeholder = "Email", #id = "lblEmail", #class = "label" } })
#Html.EditorFor(model => model.Orders.CustomerEmail, new { htmlAttributes = new { #type = "text", #min = 0, #value = "", #placeholder = "Email", #name = "cust_email", #id = "cust_email", #required = "" } })
#Html.ValidationMessageFor(model => model.Orders.CustomerEmail, "", new { #class = "text-danger" })
</div>
</div>
<div class="row">
<div class="col-lg-8">
#Html.LabelFor(model => model.Orders.DeliveryAddress, new { htmlAttributes = new { #placeholder = "Delivery Address", #id = "lblAddress", #class = "label" } })
#Html.EditorFor(model => model.Orders.DeliveryAddress, new { htmlAttributes = new { #type = "text", #min = 0, #value = "", #placeholder = "Address", #name = "cust_address", #id = "cust_Address", #required = "" } })
#Html.ValidationMessageFor(model => model.Orders.DeliveryAddress, "", new { #class = "text-danger" })
</div>
</div>
<div class="row">
<div class="col-md-offset-4 col-md-4">
<button id="btnSave" name="action" value="confirm">Confirm Order</button>
</div>
</div>
}
</div>
</div>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script>
jQuery(document).ready(function() {
setTimeout(function() {
var sum1 = 0;
$("#calculate-table tr").not(':first').each(function () {
sum1 += getnum($(this).find("td:eq(4)").text());
function getnum(t) {
if (isNumeric(t)) {
return parseInt(t, 10);
}
return 0;
function isNumeric(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
}
});
$("#total_price").val(sum1);
}, 1000);
});
function Remove(button) {
//Determine the reference of the Row using the Button.
var row = $(button).closest("TR");
var name = $("TD", row).eq(0).html();
if (confirm("Do you want to delete: " + name)) {
//Get the reference of the Table.
var table = $("#calculate-table")[0];
//Delete the Table row using it's Index.
table.deleteRow(row[0].rowIndex);
}
};
$("body").on("click", "#btnSave", function () {
//Loop through the Table rows and build a JSON array.
var orderProducts = new Array();
$("#calculate-table tr").each(function () {
var row = $(this);
var products = {};
products.ProductID = row.find("td").eq(0).html();
products.OrderUnits = row.find("td").eq(1).html();
products.TotalSum = row.find("td").eq(2).html();
products.DiscountVal = row.find("td").eq(3).html();
products.NetSum = row.find("td").eq(4).html();
orderProducts.push(products);
});
//Send the JSON array to Controller using AJAX.
$.ajax({
type: "POST",
url: "/Product/ConfirmOrder",
data: JSON.stringify(orderProducts),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (json) {
if (json.isRedirect) {
window.location.href = json.redirectUrl;
}
}
});
});
</script>
and my actionresult like this
[HttpPost]
public JsonResult ConfirmOrder(ConfirmOrderCustomModel model)
{
using(dbcontext = new CDBContext())
{
dbcontext.Orders.Add(new Model.Orders
{
ShippingDate = model.Orders.ShippingDate,
OrderTotal = model.Orders.OrderTotal,
CustomerName = model.Orders.CustomerName,
CustomerPhone = model.Orders.CustomerPhone,
CustomerEmail = model.Orders.CustomerEmail,
DeliveryAddress = model.Orders.DeliveryAddress,
OrderStatus = true
});
dbcontext.SaveChanges();
int id = dbcontext.Orders.Max(odr => odr.ID);
DataTable dt = (DataTable)Session["tblCart"];
List<DataRow> list = new List<DataRow>(dt.Select());
foreach (var item in model.SalesModel)
{
dbcontext.OrderProducts.Add(new OrderProducts
{
OrderUnits = item.OrderUnits,
TotalSum = item.TotalSum,
DiscountVal = item.DiscountVal,
NetSum = item.NetSum,
ProductID = item.ProductID,
OrderID = id
});
dbcontext.SaveChanges();
}
return Json(new
{
redirectUrl = Url.Action("Dashboard", "Admin"),
isRedirect = true
});
}
}
any help is appreciated

Cascading Drop Down List - ASP.NET MVC

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!

Passing value from a viewbag to a view

I'm trying to pass value from a view bag to the view create.
Controller
public ActionResult Create()
{
ViewBag.BanhoTosaId = new SelectList(db.BanhoTosas, "BanhoTosaId", "Tipo");
if (ViewBag.BanhoTosaId.SelectedValue != null)
{
BanhoTosa BT = db.BanhoTosas.Find(ViewBag.BanhoTosaId);
decimal valorSoma = BT.Valor + 10;
ViewBag.Total = valorSoma;
}
else
{
ViewBag.Total = 0;
}
return View();
}
view
<div class="form-group">
#Html.LabelFor(model => model.Total, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Total, new { htmlAttributes = new { #class = "form-control", value = "#ViewBag.Total" } })
#Html.ValidationMessageFor(model => model.Total, "", new { #class = "text-danger" })
</div>
</div>
In case BT will get the value in the BanhoTosa table and add 10, and then will return the value of the sum in the viewbag.Total.
But in view the #Html.EditorFor is receiving nothing
How can i do for the editorfor receive the value from the viewbag.total?
Thank's Guy's

MVC Edit form with dynamic dropdown list - How to set initial values [duplicate]

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)

Categories

Resources