Trying to get the selection of a dropdown list - c#

I'm trying to get the selection from the drop-down list and save it into the database as its corresponding primary key.
When the user makes a selection, I am unable to use that selection. I think I am not collecting the correct information in my controller.
Here is my view:
<div class="form-group">
#Html.LabelFor(model => model.Type.TypeName, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("Types", ViewBag.Types as SelectList, new { htmlAttributes = new { #class = "form-control" } } )
#Html.ValidationMessageFor(model => model.Type.TypeName, "", new { #class = "text-danger" })
</div>
</div>
Here is my controller
public ActionResult Create(CreateCommunicationViewModel commmodel){
...
var typeIDquery = db.Types.Where(g => g.TypeName == commmodel.Type.TypeName).Select(g => g.TypeID);
typeID = typeIDquery.AsEnumerable().FirstOrDefault().Trim().ToString();

I am not sure if you posted your complete code of your view but I think you are missing the HTML form:
#using (Html.BeginForm("Create", "YourControllerName", FormMethod.Get)) {....}
And in your Create method your parameter name has to match the name of dropdown list you are trying to catch:
public ActionResult Create(string Types){....}
The 'Types' parameter at your action method should be the selected value from the dropdown list.

Related

How to delete an item from database without actually deleting it?

I have been working on an ASP.NET MVC 5 web application using Entity Framework 6 as an assignment for my Business Programming II class. Despite the fact that I know very little about programming, I have been making progress, but I have run into trouble. I am supposed to write CRUD operations for an online storefront based on the Northwind Traders database. I already have working code for reading from the database as well as adding and updating items in the database. Where I'm struggling is deleting items. The following requirement is listed in the assignment description:
Delete a product by making it discontinued so that the information is displayed in the database. Do NOT actually delete a product from the database.
I've tried a couple things to try and make this work, but all have failed for various reasons.
Here's the code to my current Delete View (ignore any strange HTML formatting decisions, right now I'm focused on getting this functional):
#model NWTradersWeb.Models.Product
#{
ViewBag.Title = "Delete";
}
<h2>Delete</h2>
<h3>Are you sure you want to delete this?</h3>
<div>
<h4>Product: #Html.DisplayFor(model => model.ProductName)</h4>
<hr />
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-actions">
<input type="submit" value="Yes" class="btn btn-dark" /> |
#Html.ActionLink("Back to List", "Index")
</div>
}
</div>
I have tried editing my ProductsController.cs to manually set the Discontinued attribute to true as follows:
public ActionResult Delete(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Product product = db.Products.Find(id);
if (product == null)
{
return HttpNotFound();
}
return View(product);
}
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(int id)
{
Product product = db.Products.Find(id);
product.Discontinued = true;
db.SaveChanges();
return RedirectToAction("Index");
}
This works, but if I run the Edit operation on the same product I'm unable to undo the change. I can deselect the Discontinued checkbox but it does not save after I submit the changes and the Index page still shows the product as discontinued.
Here's my code for the Edit View and corresponding ProductsController.cs methods, I'm unsure if these have anything to do with my problem but I will include them anyway:
View:
#model NWTradersWeb.Models.Product
#{
ViewBag.Title = "Edit";
}
<h2>Edit</h2>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Product: #Html.DisplayFor(model => model.ProductName)</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
#Html.HiddenFor(model => model.ProductID)
<div class="form-group">
#Html.LabelFor(model => model.SupplierID, "SupplierID", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("SupplierID", null, htmlAttributes: new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.SupplierID, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.CategoryID, "CategoryID", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("CategoryID", null, htmlAttributes: new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.CategoryID, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.QuantityPerUnit, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.QuantityPerUnit, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.QuantityPerUnit, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.UnitPrice, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.UnitPrice, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.UnitPrice, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.UnitsInStock, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.UnitsInStock, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.UnitsInStock, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.UnitsOnOrder, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.UnitsOnOrder, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.UnitsOnOrder, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.ReorderLevel, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.ReorderLevel, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.ReorderLevel, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Discontinued, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
<div class="checkbox">
#Html.EditorFor(model => model.Discontinued)
#Html.ValidationMessageFor(model => model.Discontinued, "", new { #class = "text-danger" })
</div>
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Save" class="btn btn-default" />
</div>
</div>
</div>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
Controller Methods:
public ActionResult Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Product product = db.Products.Find(id);
if (product == null)
{
return HttpNotFound();
}
ViewBag.CategoryID = new SelectList(db.Categories, "CategoryID", "CategoryName", product.CategoryID);
ViewBag.SupplierID = new SelectList(db.Suppliers, "SupplierID", "CompanyName", product.SupplierID);
return View(product);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "ProductID,ProductName,SupplierID,CategoryID,QuantityPerUnit,UnitPrice,UnitsInStock,UnitsOnOrder,ReorderLevel,Discontinued")] Product product)
{
if (ModelState.IsValid)
{
db.Entry(product).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.CategoryID = new SelectList(db.Categories, "CategoryID", "CategoryName", product.CategoryID);
ViewBag.SupplierID = new SelectList(db.Suppliers, "SupplierID", "CompanyName", product.SupplierID);
return View(product);
}
My professor also alluded to making the Delete operation redirect to a simpler Edit page where we could toggle the Discontinued attribute. I think he may be alluding to a partial view but we have not covered that to my knowledge.
Please note: I consider myself a novice when it comes to programming. I've taken other classes but the instructors focused more on syntax than concepts and as such my foundation is incredibly weak. I might be clueless about certain things that other people take for granted. I want to go back and study the fundamentals after I graduate and self-study, but this is a required class for a degree that is almost completely unrelated to programming. Any tips, hints, even a nudge in the right direction would be greatly appreciated.
Your Delete logic seems fine. What I would look at in more detail is your Edit.
Overall I am not a fan of ever passing Entities between the server and the view, especially accepting an entity from the view. This is generally a bad practice because you are trusting the data coming from the view, which can easily be tampered with. The same when passing data from a view to server, this can lead to accidentally exposing more information about your domain (and performance issues) just by having some "sloppy" JavaScript or such converting the model into a JSON model to inspect client-side. The recent case of the journalist being accused of "hacking" because they found extra information via the browser debugger in a Missouri government website outlines the kind of nonsense that can come up when server-side code has the potential to send far too much detail to a browser.
In any case, in your Edit method when you accept the bound Product after deactivating the Discontinued flag, what values are in that Entity model? For instance if you use Delete to set Discontinued to "True", then go to the Edit view for that product and un-check that input control and submit the form, in your "product" coming in the Edit page, what is the state of the product.Discontinued?
If the value is still "True" then there is a potential problem with your page binding where the EditorFor is not linking to that flag properly or the value is not deserializing into the Product entity. (a private or missing setter?)
If it is coming back with what should be the correct value, then I would look at changing how you update entities. Code like this:
db.Entry(product).State = EntityState.Modified;
db.SaveChanges();
... is inherently dangerous as "product" is not an entity, it is a deserialized set of values used to populate an entity class. Ideally when updating data you would provide a ViewModel that won't be confused with an Entity class and contain just the fields that are allowed to be updated. Using your current code though with the entity class serving as that view model I would suggest something more like:
var dataProduct = db.Products.Single(x => x.Id == product.Id);
dataProduct.ProductName = product.ProductName;
dataProduct.Discontinued = product.Discontinued;
// ...
db.SaveChanges();
When it comes to possibly allowing the user to change FKs for things like categories, then you should eager load those relationships, compared the FK IDs then load and re-associate those "new" relationships in the entity loaded from data state. (Don't just replace the FK values.)
The reason for doing this rather than attaching and setting the state to modified:
We perform a validation when loading the entity. If we get back an Id that doesn't exist, we can handle that exception. We can also filter data to ensure that the current user actually has permission to see the requested ID and can end a session if it looks like someone is tampering with data.
We only update values that we allow to change, not everything in the entity. We can also validate to ensure that the values provided are fit for purpose before making changes.
When copying values across, EF will only generate UPDATE statements for values that actually change if any actually change. Attaching and setting the entity state to Modified or using Update will always generate an UPDATE statement replacing all values whether anything changed or not. (can have negative impacts on triggers or hooks in the DbContext for things like Auditing)

The ViewData item that has the key 'HousingId' is of type 'System.Int32' but must be of type 'IEnumerable<SelectListItem>'."

I have a MVC application I'm working on. I have an Application Create View that works just fine. But I wanted to create a partial view so I could call it in the Index. However that partial view throws
System.InvalidOperationException: 'The ViewData item that has the key 'HousingId' is of type 'System.Int32' but must be of type 'IEnumerable'
on this line of code:
#Html.DropDownList("HousingId", (IEnumerable<SelectListItem>)ViewBag.Housings, htmlAttributes: new { #class = "form-control" })
Yet that line of code works fine in the normal Create view. Here is my controller:
public ActionResult Create()
{
var housings = new SelectList(_db.Housings.ToList(), "HousingId", "Name");
ViewBag.Housings = housings;
return View();
}
What am I missing?
EDIT: Here is how I'm passing the partial
#model IEnumerable<Housing_RedBadgeMVC.Models.ApplicationModels.ApplicationListItem>
...
#foreach (var item in Model)
{
<div class="create-housing-container">
<p style="color: white; font-size: 12px;">
Here you can view current applications for specific housing,
if you'd like to fill out an application please click
#Html.Partial("_ApplicationCreate", item)
</p>
</div>
}
...
And what's in the partial:
#model Housing_RedBadgeMVC.Models.ApplicationModels.ApplicationListItem
...
#using (Html.BeginForm("Create", "Application", new { id = Model.HousingId }))
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.HousingId, "Housing", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("HousingId", (IEnumerable<SelectListItem>)ViewBag.Housings, htmlAttributes: new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.HousingId, "", new { #class = "text-danger" })
</div>
</div>
}
...
It says that the Dropdownlist must be List where as you are just passing single object like var
Change this:
var housings = new SelectList(_db.Housings.ToList(), "HousingId", "Name");
to
IEnumerable<SelectListItem> housings = new SelectList(_db.Housings.ToList(), "HousingId", "Name");
EDIT:
Try this:
IEnumerable<SelectListItem> housings = db.Housings.Select(
b => new SelectListItem { Value = b.HousingId, Text = b.Name}).ToString();
ViewBag.Housings = housings;

Scaffolded model/view: The ViewData item that has the key 'COLUMN' is of type 'System.String' but must be of type 'IEnumerable<SelectListItem>'

I know that there have been a number of questions asked similar to this, but they all seem to be dealing with a page that loads fine and has problems when trying to POST. I'm using scaffolded code in an MVC project with a code first database. The dropdown that's failing is supposed to be filled from a foreign key relationship, there are two other dropdowns using exactly the same code but with different names, and commenting shows that only this one dropdown is bad. This should be on an edit but the page doesn't even load to be submitting data like the other questions do. Both the create and the edit pages do not load.
With all that said, this is the controller:
public ActionResult Edit(long? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Person person = db.People.Find(id);
if (person == null)
{
return HttpNotFound();
}
ViewBag.Title = new SelectList(db.Job_Title, "Id", "Title", person.Title);
ViewBag.Location = new SelectList(db.Locations, "Id", "Name", person.Location);
ViewBag.Manager = new SelectList(db.Managers, "Id", "Name", person.Manager);
return View(person);
}
and this is a section of the corresponding view:
<div class="form-group">
#Html.LabelFor(model => model.Title, "Title", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#*FIXME: Commenting the line below will allow the page to load fine*#
#Html.DropDownList("Title", null, htmlAttributes: new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.Title, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Location, "Location", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("Location", null, htmlAttributes: new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.Location, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Manager, "Manager", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("Manager", null, htmlAttributes: new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.Manager, "", new { #class = "text-danger" })
</div>
</div>
I'd love to know why just the title dropdown kills the page while the other 2 are completely fine. I'd also love to know why scaffolded code was generated with an error!
The error means that the value of ViewBag.Title is null or not an IEnumerable<SelectListItem>.
This will be happening because your view includes
#{
ViewBag.Title = ".....";
#
which overwrites the value you set in the GET method.

Display a list from controller method viewbag to a list in view

I have following GET method in my controller:
public ActionResult GetLinesByDestination()
{
destinationService = new DestinationService();
ViewBag.Destination_id = new SelectList(destinationService.All(), "Destination_id", "city");
lineService = new LineService();
ViewBag.Lines = new SelectList(lineService.All(), "line_id", "arrival");
return View();
}
POST method:
[HttpPost]
public ActionResult GetLinesByDestination(int? Destination_id)
{
destinationService = new DestinationService();
ViewBag.Destination_id = new SelectList(destinationService.All(), "Destination_id", "city", Destination_id);
lineService = new LineService();
ViewBag.Lines = new SelectList(lineService.GetLinesByDestination(Convert.ToInt16(Destination_id)), "line_id", "arrival").ToList();
return View();
}
View code:
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.Label("Destinations", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("Destination_id", null, "- Select a destination you want to depart from -", htmlAttributes: new { #class = "form -control" })
#Html.ValidationMessage("Destination_id", "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.Label("Lines", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("Lines", null, htmlAttributes: new { #class = "form-control" })
#Html.ValidationMessage("Lines", "", new { #class = "text-danger" })
</div>
All this does when executing the GET is retrieve a list of all destinations and all lines in my database. However, when clicking 'submit' and so the POST method is executed, only the lines that depart from the by the user selected destination should be shown. This is fully functional.
Now my actual question:
The Destination_id ViewBag should remain a dropdownlist in the view, since the user has to pick an option from here. I'd however like the Lines shown as a list (like < li >) on the view, so not a dropdownlist. How do I do this? I have tried some foreach loops earlier but that did not work.
Iterating Through Your SelectList
You should be able to just iterate through your ViewBag collection as expected by referring to the Text and Value properties set when binding to your SelectList:
#if (ViewBag.Lines != null) {
<ul>
#foreach (var line in ViewBag.Lines){
<li>
#line.Text - #line.Value
</li>
}
</ul>
}
For ease of use, you might consider actually binding this collection to a specific class instead of a SelectList, which would not only give you strong typing within your View, but it would allow you to include / reference properties besides just Text and Value.
Binding Your Values
As far as actually posting values that were "selected", you would likely want to consider outputting a checkbox value for each list item and then store properties related to that item, which could be posted to your form:
<ul>
#foreach (var line in ViewBag.Lines){
<li>
#line.Text - #line.Value
<input type='checkbox' name='lines[]' value='#line.Value' / >
</li>
}
</ul>
This would assume that you would want to post back an array of values that represented the "value" of each of the lines that were selected. Likewise, if you wanted to only include a single option, you could replace these with radio buttons and ensure that the name attribute properly binds to your destination_id property:
<ul>
#foreach (var line in ViewBag.Lines){
<li>
#line.Text - #line.Value
<input type='radio' name='Destination_id' value='#line.Value' / >
</li>
}
</ul>

Creating Forms that use asp.Identity to pre-populate some data and create new entry to db

I have a site in progress that is using ASP.Identity to create new users. I have a secondary table with more user information I would like to be populated once the account is registered. As I already have the id and email, I don't need to ask for these again but can't get the second form to pass the data through the Create Razor page, even though it's displaying on the form itself.
I'm getting an error message when I submit saying the "LoginID is required", so how do I get the form to post with the value of userLoginId?
Create Page
var userLoginId = User.Identity.GetUserId();
<div class="form-horizontal">
<h4>nrLogins</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.LoginID, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => userLoginId, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => userLoginId, "", new { #class = "text-danger" })
</div>
</div>
LoginController
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "LoginID,Email,FirstName,LastName,DateOfBirth,Address1,Address2,Address3,Address4,Address5,PostCode,PhoneMobile,PhoneOther,UserSearchable,SiteRoleType,AccountActive,AccountCreatedDate,AccountEditedDate,AccountDeletedDate")] dbLogin dbLogin)
{
if (ModelState.IsValid)
{
db.dbLogins.Add(dbLogin);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(dbLogin);
}
Thanks!
You need to specify the name attribute for the control otherwise it default to your variable name which is userLoginId instead of LoginId, so you can do the following:
#Html.EditorFor(model => userLoginId, null, "LoginId", new { htmlAttributes = new { #class = "form-control" } })
If you don't want the user to be able to see or edit the details you can pass it as a hidden field
#Html.Hidden("LoginId", userLoginId)

Categories

Resources