How to get values of disabled dropdownFor in mvc controller - asp.net-mvc

I have a dropdownListFor controls which are cascade in nature on edit i do need to disabled the below cascaded dropdown lists until the values get changed from the first one , so below is my code of dropdown list
<div class="form-group">
#Html.LabelFor(model => model.Program_Id, "Program_Id", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("Program_Id", null, htmlAttributes: new { #class = "form-control", #id = "ddlPrograms" })
#Html.ValidationMessageFor(model => model.Program_Id, "", new { #class = "text-danger" })
</div>
</div>
I am making them disable using javascript
document.getElementById("ddlYear").disabled = true;
document.getElementById("ddlBlocks").disabled = true;
document.getElementById("ddlModules").disabled = true;
But on Edit when I submit the forms instead of selected value they send 0 to the controller . how to fix that issue if i am using hidden field then how i would be able to access this hidden field value as i am using entity framework and below is my controller edit post method
public async Task<ActionResult> Edit([Bind(Include = "Course_Id,Course_Name,Course_Code,Course_Visibility,Course_Start_Date,Course_End_Date,Block_Id,Module_Id,Program_Id,Year,Course_Description,Course_Image,Course_Category_Id,Course_Content_File_Path,Course_announcement,Course_Tags,Status,Course_Short_Name,Date_Created,Date_Modified")] Courses courses)
{
if (ModelState.IsValid)
{
db.Entry(courses).State = EntityState.Modified;
if (db.SaveChanges() > 0)
{
TempData["UpdatedMessage"] = "Updated Successfully";
}
// await db.SaveChangesAsync();
return RedirectToAction("Index");
}
ViewBag.Block_Id = new SelectList(db.Blocks, "Id", "Name", courses.Block_Id);
ViewBag.Course_Category_Id = new SelectList(db.Courses_Category, "Id", "Category_Name", courses.Course_Category_Id);
ViewBag.Module_Id = new SelectList(db.Moduels, "Id", "Name", courses.Module_Id);
ViewBag.Program_Id = new SelectList(db.Programs, "Id", "Program_Title", courses.Program_Id);
ViewBag.Year = new SelectList(db.Years, "Id", "Name", courses.Year);
return View(courses);
}
Thanks in advance

Related

There is no ViewData item of type 'IEnumerable<SelectListItem>' that has the key 'MembershipTypesId'

View class
<div class="editor-label">
#Html.LabelFor(model => model.MembershipTypesId, "MembershipTypesId", htmlAttributes: new { #class = "control-label col-md-2" })
</div>
<div class="editor-field">
#Html.DropDownList("MembershipTypesId", null, htmlAttributes: new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.MembershipTypesId, "", new { #class = "text-danger" })
</div>
UsersController
public ActionResult Register(Customers customer)
{
if (ModelState.IsValid)
{
using (CDBContext dc = new CDBContext())
{
dc.Customers.Add(customer);
dc.SaveChanges();
ModelState.Clear();
customer = null;
ViewBag.MembershipTypesId = new SelectList(dc.MembershipTypes, "MembershipTypesId", "Name");
ViewBag.Message = "Successfully Registration Done";
}
}
return View(customer);
}
I used the same code for the others view and controller but somehow only this got the error. I tried to remove the null but it still the same.
What your error message suggest is that you are don't have ViewData that you should pass on this DropDownList:
#Html.DropDownList("MembershipTypesId", null, htmlAttributes: new { #class = "form-control" })
It is looking for ViewData with name MembershipTypesId
Your code on controller is correct IF you don't have problem on ModelState, but what if you have an error in your ModelState? Where is your ViewData that you need to pass back on your View?
This should be populated before you return to your View from your Controller:
public ActionResult Register(Customers customer)
{
if (ModelState.IsValid)
{
//Business Logic
}
ViewBag.MembershipTypesId = new SelectList(dc.MembershipTypes, "MembershipTypesId", "Name");
return View();
}

insert drop down list value in database in asp.net mvc

i want insert drop down list value in database from controller:
public ActionResult PostMessage(ViewModel vm)
{
Models.Message messagetoPost = new Models.Message();
ViewBag.Userlist = new SelectList(dbContext.Users, "Id", "UserName");
ViewBag.Userlist = messagetoPost.MessageTosend;
dbContext.Messages.Add(messagetoPost);
dbContext.SaveChanges();
}
View
#Html.DropDownList("Userlist", null, htmlAttributes: new { #class = "form-control" })
You are using the wrong signature. You need the selected value in your ViewModel, for example UserId:
#Html.DropDownList("UserId", ViewBag.Userlist, null, htmlAttributes: new { #class = "form-control" })
or better yet
#Html.DropDownListFor(m => m.UserId, ViewBag.Userlist, "Select User", htmlAttributes: new { #class = "form-control" })
Finally, you have some other errors (assuming this is the POST method where you want to save). Copy the posted viewmodel fields into your Message entity and save (if no errors):
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult PostMessage(ViewModel vm)
{
if (ModelState.IsValid)
{
Models.Message messagetoPost = new Models.Message
{
UserId = vm.UserId;
... other fields
};
dbContext.Messages.Add(messagetoPost);
dbContext.SaveChanges();
return RedirectToAction("Index");
}
// Failed, reset dropdown and return view with errors...
ViewBag.Userlist = new SelectList(dbContext.Users, "Id", "UserName");
return View(complianceItemViewModel);
}
#Html.DropDownList("Userlist", null, htmlAttributes: new { #class = "form-control" })
change
#Html.DropDownList("User",ViewBag.Userlist, null, htmlAttributes: new { #class = "form-control" })
In this Place, "User" is the name of the Dropdown name
ViewBag.UserList is the options for the dropdown list
null is placed .if you need set the selected value of the dropdown
Dropdown Control Name and ViewBag name is same than data not bind properly

How to save dropdown values in database in asp.net MVC

When I select category from dropdown it is not saving in database. In database it is showing 101 for all values
MY view.cshtml is
<h4>RecStock</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.Category, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
<div class="editor-field">
#Html.DropDownList("Category",null, new { #class = "form-control" } )
</div>
#Html.ValidationMessageFor(model => model.Category, "", new { #class = "text-danger" })
</div>
</div>
My Controller is
public ActionResult Create()
{
ViewBag.Category = new SelectList(db.ProductDetails, "id", "Category");
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "Category,ProductName,ReceiveQty,Date")] RecStock recStock)
{
if (ModelState.IsValid)
{
db.RecStocks.Add(recStock);
ViewBag.Category = new SelectList(db.ProductDetails, "id", "Category", recStock.id);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(recStock);
}
You should be using "DropDownListFor" and assign the selected dropdown value to the corresponding model property, like this:
#Html.DropDownListFor(m => m.MyModelProperty, new SelectList(Model.ListOfStuff, "ListOfStuffId", "ListOfStuffName"), string.Empty, new {#class = "form-control", id = "myList"})

ASP.NET MVC EntityFramework How to Save New Object along with Multiple Child Objects in Create

I'm using the database first method. I have a single form where data is entered. From this, a new "form entry", a new customer and 3 new addresses will be created. 2 addresses are associated with the customer, 1 address is associated with the form entry as a whole, and the customer is associated with the form entry.
The question (revision 2):
How does one usually go about preparing fields that reference objects that will be created simultaneously -- "hey, these id fields right here will reference objects created simultaneously from the same, current dataset you're being built from"?
(
i.e. How would one normally do something like the following in MVC:
1) create each of the 3 addresses as new addresses;
2) associate 2 of them with a new customer via checkoutForm.Customer.HomeAddressId and checkoutForm.Customer.MailingAddressId;
3) associate the other with checkoutForm.PlaceOfUseAddressId itself;
4) save the customer; then
5) associate the customer with checkoutForm.CustomerId; and, finally
6) save the checkoutForm itself,
while not making ModelState.IsValid false in the meantime because checkoutForm.CustomerId and each x.AddressId are required but are initially null?
)
Any references to something that explains a procedure for simultaneously creating multiple dependent objects like this would be fantastic!
Edit: I removed the bind attribute from the parameter for Create(), and that makes all the data pull into the correct fields. The dropdownlists are properly grabbing their respective StateId.
Currently, ModelState.IsValid reports false on submit. The required ids of the child objects are null and such (which makes sense, because that's what I'm trying to figure out how to tell .NET -- here's an object association that will be created once we have the data).
Edit2: I refined the question yet again, now that I'm getting closer to what I actually need to fix: ModelState.IsValid == false, because the pertinent ids for checkoutForm and Customer that reference dependencies are null.
Depiction of the model behind this form:
Here's the form itself:
( Note the 2 dropdownlists. Everything else is a textbox for strings, ints, or dates. )
What I have for the controller so far (not much beyond what the scaffolding created):
// GET: CheckoutForms/Create
public ActionResult Create()
{
ViewBag.HomeStateList = new SelectList(db.RT_STATE_LIST, "ST_SEQ", "ST_ABBR", 2);
ViewBag.MailingStateList = new SelectList(db.RT_STATE_LIST, "ST_SEQ", "ST_ABBR", 2);
return View();
}
// POST: CheckoutForms/Create
[HttpPost]
[ValidateAntiForgeryToken]
// public ActionResult Create([Bind(Include = "Customer.FirstName,Customer.LastName,VacuumNumber,Customer.Phone,Customer.DriversLicense,Customer.HomeAddress.Street,Customer.HomeAddress.City,Customer.HomeAddress.StateId,Customer.MailingAddress.Street,Customer.MailingAddress.City,Customer.MailingAddress.StateId,Customer.MailingAddress.PostalCode,PlaceOfUseAddress.Street,PlaceOfUseAddress.City,PlaceOfUseAddress.StateId,PickupDate,DueDate,ReturnedDate,EnteredBy,EnteredDate,ModifiedBy,ModifiedDate")] CheckoutForm checkoutForm)
public ActionResult Create(CheckoutForm checkoutForm)
{
if (ModelState.IsValid)
{
checkoutForm.PlaceOfUseAddress.StateId = 1;
// !!! Need to be given correct value once authorization is set up.
checkoutForm.EnteredBy = -1;
checkoutForm.ModifiedBy = -1;
checkoutForm.EnteredDate = System.DateTime.Now;
checkoutForm.ModifiedDate = System.DateTime.Now;
// ??? db.Addresses.Add(checkoutForm.PlaceOfUseAddress);
// ??? db.Addresses.Add(checkoutForm.Customer.HomeAddress);
// ??? db.Addresses.Add(checkoutForm.Customer.MailingAddress);
// ??? db.SaveChanges();
// ??? checkoutForm.PlaceOfUseAddressId = checkoutForm.PlaceOfUseAddress.AddressId;
// ??? checkoutForm.Customer.HomeAddressId = checkoutForm.Customer.HomeAddress.AddressId;
// ??? checkoutForm.Customer.MailingAddressId = checkoutForm.Customer.MailingAddress.AddressId;
// ??? db.Customers.Add(checkoutForm.Customer);
// ??? db.SaveChanges();
db.CheckoutForms.Add(checkoutForm);
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.HomeStateList = new SelectList(db.RT_STATE_LIST, "ST_SEQ", "ST_ABBR", checkoutForm.Customer.HomeAddress.StateId);
ViewBag.MailingStateList = new SelectList(db.RT_STATE_LIST, "ST_SEQ", "ST_ABBR", checkoutForm.Customer.MailingAddress.StateId);
return View(checkoutForm);
}
Finally, here are the form elements from the view (with everything else stripped out:
#using (Html.BeginForm())
{
#Html.HiddenFor(model => model.CustomerId)
#Html.HiddenFor(model => model.PlaceOfUseAddressId)
#Html.HiddenFor(model => model.Customer.HomeAddressId)
#Html.HiddenFor(model => model.Customer.MailingAddressId)
#Html.HiddenFor(model => model.EnteredBy)
#Html.HiddenFor(model => model.EnteredDate)
#Html.HiddenFor(model => model.ModifiedBy)
#Html.HiddenFor(model => model.ModifiedDate)
<!-- Name and Vacuum Number -->
#Html.EditorFor(model => model.Customer.FirstName, new { htmlAttributes = new { #class = "form-control checkout" } })
#Html.EditorFor(model => model.Customer.LastName, new { htmlAttributes = new { #class = "form-control checkout" } })
#Html.EditorFor(model => model.VacuumNumber, new { htmlAttributes = new { #class = "form-control checkout" } })
<!-- Driver's License -->
<!-- Phone Number -->
#Html.EditorFor(model => model.Customer.Phone, new { htmlAttributes = new { #class = "form-control checkout" } })
#Html.EditorFor(model => model.Customer.DriversLicense, new { htmlAttributes = new { #class = "form-control checkout" } })
<!-- Place of Use Address -->
#Html.EditorFor(model => model.PlaceOfUseAddress.Street, new { htmlAttributes = new { #class = "form-control checkout" } })
#Html.EditorFor(model => model.PlaceOfUseAddress.City, new { htmlAttributes = new { #class = "form-control checkout" } })
<!-- Customer's Home Address -->
#Html.EditorFor(model => model.Customer.HomeAddress.Street, new { htmlAttributes = new { #class = "form-control checkout" } })
#Html.EditorFor(model => model.Customer.HomeAddress.City, new { htmlAttributes = new { #class = "form-control checkout" } })
#Html.DropDownListFor(model => model.Customer.HomeAddress.StateId, ViewBag.HomeStateList as SelectList, htmlAttributes: new { #class = "form-control checkout" })
<!-- Customer's Mailing Address -->
#Html.EditorFor(model => model.Customer.MailingAddress.Street, new { htmlAttributes = new { #class = "form-control checkout" } })
#Html.EditorFor(model => model.Customer.MailingAddress.City, new { htmlAttributes = new { #class = "form-control checkout" } })
#Html.DropDownListFor(model => model.Customer.MailingAddress.StateId, ViewBag.MailingStateList as SelectList, htmlAttributes: new { #class = "form-control checkout" })
#Html.EditorFor(model => model.Customer.MailingAddress.PostalCode, new { htmlAttributes = new { #class = "form-control checkout" } })
<!-- Dates Picked Up, Due, and Returned -->
#Html.EditorFor(model => model.PickupDate, new { htmlAttributes = new { #class = "form-control checkout" } })
#Html.EditorFor(model => model.DueDate, new { htmlAttributes = new { #class = "form-control checkout" } })
#Html.EditorFor(model => model.ReturnedDate, new { htmlAttributes = new { #class = "form-control checkout" } })
}
Figured it out.
On the View, the Hidden fields are connected with the foreign key address ids (as I had them), but must also be pre-populated with bogus values (so they aren't null), like so:
#Html.HiddenFor(model => model.CustomerId, new { #Value = "0" })
#Html.HiddenFor(model => model.PlaceOfUseAddressId, new { #Value = "0"})
#Html.HiddenFor(model => model.Customer.HomeAddressId, new { #Value = "0" })
#Html.HiddenFor(model => model.Customer.MailingAddressId, new { #Value = "0" })
Then, the procedure on the Controller ends up being fairly straightforward, because MVC is otherwise successfully handling all the pieces. I just need to save and associate them, children on up:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(CheckoutForm checkoutForm)
{
Address PlaceOfUse = new Address();
Address HomeAddy = new Address();
Address MailingAddy = new Address();
Customer Client = new Customer();
if (ModelState.IsValid)
{
// Not currently available to the user to be filled in by them
checkoutForm.PlaceOfUseAddress.StateId = 1;
// !!! Need to be given correct value once authorization is set up.
checkoutForm.EnteredBy = TestAccountId;
checkoutForm.ModifiedBy = TestAccountId;
checkoutForm.EnteredDate = System.DateTime.Now;
checkoutForm.ModifiedDate = System.DateTime.Now;
PlaceOfUse = checkoutForm.PlaceOfUseAddress;
HomeAddy = checkoutForm.Customer.HomeAddress;
MailingAddy = checkoutForm.Customer.MailingAddress;
db.Addresses.Add(PlaceOfUse);
db.Addresses.Add(HomeAddy);
db.Addresses.Add(MailingAddy);
db.SaveChanges();
checkoutForm.PlaceOfUseAddressId = PlaceOfUse.AddressId;
checkoutForm.Customer.HomeAddressId = HomeAddy.AddressId;
checkoutForm.Customer.MailingAddressId = MailingAddy.AddressId;
Client = checkoutForm.Customer;
db.Customers.Add(Client);
db.SaveChanges();
checkoutForm.CustomerId = Client.CustomerId;
db.CheckoutForms.Add(checkoutForm);
db.SaveChanges();
return RedirectToAction("Index");
}
else {
// To review in debug mode, when there are problems
//var errors = this.ModelState.Keys.SelectMany(key => this.ModelState[key].Errors);
ViewBag.HomeStateList = new SelectList(db.RT_STATE_LIST, "ST_SEQ", "ST_ABBR", checkoutForm.Customer.HomeAddress.StateId);
ViewBag.MailingStateList = new SelectList(db.RT_STATE_LIST, "ST_SEQ", "ST_ABBR", checkoutForm.Customer.MailingAddress.StateId);
return View(checkoutForm);
}
}
Plus, removing the "Bind" attribute from Create()'s parameter made it all a lot easier.

Dropdownlist in MVC with Where cluase in entities

I am new to MVC. I want to fill Dropdownlist only where Account_Type = "D".
Here is my Edit.cshtml
<div class="form-group">
#Html.LabelFor(model => model.Account_Code, "Account_Code", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("Account_Code", null, htmlAttributes: new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.Account_Code, "", new { #class = "text-danger" })
</div>
</div>
And here is my Edit Controller
public ActionResult Edit(int? id)
{
ViewBag.Account_Code = new SelectList(db.Chart_Of_Account, "Account_Code", "Account_Desc", student.Account_Code);
}
Use a .Where() clause to filter your data
public ActionResult Edit(int? id)
{
var accountCodes = db.Chart_Of_Account.Where(a => a.Account_Type == "D");
ViewBag.AccountCodeList = new SelectList(accountCodes , "Account_Code", "Account_Desc");
}
Note I have changed the name of the ViewBag property and removed the 3rd parameter of the SelectList contructor (its ignored when binding to a property)
Your view should be
#Html.DropDownListFor(m => m.Account_Code, (SelectList)ViewBag.AccountCodeList)

Resources