how to create a complex "Create" ActionResult in MVC - c#

I am very new to MVC and trying to do a project. I have Product model which is created from database. It has the properties like below(I am now writing all properties.)
Product
-------
ID(int)
CODE(string)
CATEGORY_ID(int)
Categories
-------
ID(int)
CODE(string)
I created the Create ActionResult for Product. And since the CATEGORY_ID is integer in the database, Visual Studio created a textbox for CATEGORY_ID. I want it to be dropdownlist which will list all the categories from the Categories table.But when the user click the Save button, it will write integer value of the selected category to Product table.
How can I do that dropdownlist? How can I pass all the categories to the Product's Create ActionResult?

You want to use a ViewModel to shape your DB model to a presentation purpose.

In model class Product add following,
[NotMapped]
public SelectList Categories { get; set; }
in view add
#Html.DropDownListFor(model => model.CategoryID, Model.Categories, "--Select--", new { #id="drpCommodity"})
fill Categories in using following
public static SelectList GetDropDownList<T>(List<T> objects, string value, string text)
{
List<SelectListItem> items = new List<SelectListItem>();
//var defaultItem = new SelectListItem();
//defaultItem.Value = Convert.ToString(-1);
//defaultItem.Text = "--Select--";
//defaultItem.Selected = true;
//items.Add(defaultItem);
List<SelectListItem> lst = objects
.Select(x =>
new SelectListItem
{
Value = x.GetType().GetProperty(value).GetValue(x).ToString(),
Text = x.GetType().GetProperty(text).GetValue(x).ToString()
}).ToList();
items.AddRange(lst);
return new SelectList(items, "Value", "Text");
}

Related

ASP.Net MVC Dropdown text generation using a Select List not populating the values and text

Using the following code i generate a select list in my controller and feed it into my view model.
var SelectListItems = om_repo.List().Select(x => {
var item = new SelectListItem();
item.Value = x.id.ToString();
item.Text = x.code;
return item;
});
createvm.allOccupations = new SelectList(SelectListItems);
Here is my view code
#Html.DropDownListFor(model => model.selectedOccupation, Model.allOccupations, "Choose one")
The output im getting is
<option>System.Web.Mvc.SelectListItem</option>
Why isnt it picking up the select list items Text and Values that are being fed. In my debugger i can see the values are set in the locals under text and value.
Because the DropDownlist doesn't want a SelectList; it wants an IEnumerable of SelectListItems.
Try just:
createvm.allOccupations = SelectListItems;
Model Class also needs to be:
public IEnumerable<SelectListItem> allOccupations { get; set; }
Not
public SelectList allOccupations { get; set; }
Scott Allen expanded on the problem here: https://odetocode.com/Blogs/scott/archive/2010/01/18/drop-down-lists-and-asp-net-mvc.aspx

Show list after select DropDownList value Razor

I've been working for a while on this, I know how to resolve it using JQuery, but I need to solve this just using server side code, I'm in a Razor View
The thing is:
I have an #Html.DropDownlist that is showing some States from USA, and once clicked one of the States from the DropDownList then I want to show some cities that belong to the State selected using other DropDownList, I'm not sure how to get the value from the selected field just using Razor syntax and then show the cities that belong to the State in other DropDownList when one State is selected, I'm using a SelectList and I have an StateID to bind the cities... I'm showing all the States inside a DropDownList that is working.
Here is my code:
These are just two classes that I'm using to fill the SelectList with some properties:
public States(int id, string name, List<string> list)
{
StateID = id;
Name = name;
Cities = list;
}
public int StateID { get; set; }
public string Name { get; set; }
public List<string> Cities { get; set; }
}
public static class Fill
{
public static List<States> GiveMeStates()
{
List<States> li = new List<States>() {
new States(1, "Alabama",new List<string> {"Adamsville", "Addison", "Anderson","Anniston", "Arab" }),
new States(2,"Alaska", new List<string> {"Anchorage","Juneau","Fairbanks","Sitka"}),
new States(3,"Arizona", new List<string> { "Avondale", "Benson", "Besbee"})
};
return li;
}
}
And now this is my Razor View:
#using RazorMVC.Models;
#{
List<States> aux = Fill.GiveMeStates();
SelectList states = new SelectList(aux, "StateID", "Name");
}
<form>
#Html.DropDownList("ddlStates", states);
</form>
If you absolutely do not want to use javascript/jQuery, you may submit the form (with the selected state id) and get the states based on the posted state id and show that.
Assuming you want to show the cities for the selected state in the same view.
#{
var stateId = Request.QueryString["ddlStates"] as string;
List<States> aux = Fill.GiveMeStates();
SelectList states = new SelectList(aux, "StateID", "Name");
List<SelectListItem> cities = new List<SelectListItem>();
if (!String.IsNullOrEmpty(stateId))
{
var state = aux.FirstOrDefault(f => f.StateID == Convert.ToInt32(stateId));
if (state != null)
{
cities = state.Cities
.Select(x => new SelectListItem {Value = x, Text = x}).ToList();
}
}
}
<label>Select a state and hit submit </label>
#using (Html.BeginForm("Index", "Home", FormMethod.Get))
{
#Html.DropDownList("ddlStates", states)
<label>Cities < /label>
#Html.DropDownList("City", cities)
<input type="submit" />
}
I personally prefer to not put a lot of C# code in the razor views. I usually create a view model and use that to pass the values needed in the view. So most of the above code you see in the view goes in my action method.
If you prefer to use jQuery/javascript (Why not ?), You may listen to the change event of the the first dropdown ,get the selected option value and send that to server via an ajax call. Let your server action method returns the states in json format and your ajax metod's call back can parse the json data and update the cities dropdown. Here is a sample to start with

How to pass the value to drop down fields in edit mode in MVC4?

Hi i have three Fields in my view.That three fields are drop down. I want to pass the value to these fields when edit button is clicked. That is the values need to pass to that drop down fields. My view is mentioned below
In my view i have many drop downs but once i know how to pass the value to one drop down means i will do for another drop downs.
For Edit i create one view in sql and connect that view as EDMX file in my application.In this view(table) i have all fields which is in Visitors Form. That view name is View_VisitorsForm.
My Model(VisitorsViewModel)
public Nullable<System.DateTime> Date { get; set; }
public System.Guid VisitingID { get; set; }
public Nullable<System.Guid> EmployeeID { get; set; }
public string EmployeeName { get; set; }
public string Description { get; set; }
My Edit Code
public ActionResult Edit(Guid ?id)
{
WafeERPNEWEntities db = new WafeERPNEWEntities();
SelectList typelist = new SelectList(db.Employees.ToList(), "EmployeeID", "DisplayName", db.Employees);
ViewData["EmployeeName"] = typelist;
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
VisitorsViewModel ObjVisitorsviewModel = new VisitorsViewModel();
View_VisitorsForm visit = db.View_VisitorsForm.Find(id);
visit.VisitingID = ObjVisitorsviewModel.VisitingID;
visit.VisitingDate = ObjVisitorsviewModel.Date;
visit.Description = ObjVisitorsviewModel.Description;
if (ObjVisitorsviewModel == null)
{
return HttpNotFound();
}
return View(ObjVisitorsviewModel);
}
My View Code
#Html.LabelFor(model => model.Date)
#Html.EditorFor(model => model.Date)
#Html.ValidationMessageFor(model => model.Date)
#Html.LabelFor(model => model.VisitingID)
#Html.EditorFor(model => model.VisitingID)
#Html.ValidationMessageFor(model => model.VisitingID)
#Html.LabelFor(model => model.EmployeeName)
#Html.DropDownList("EmployeeID", (IEnumerable<SelectListItem>)ViewData["EmployeeName"])
#Html.ValidationMessageFor(model => model.EmployeeName)
Now when i click the edit button it pass the value to this line
View_VisitorsForm visit = db.View_VisitorsForm.Find(id);
and also it getting visit.visitingID. But it is not getting the value in viewmodel .so the value will be empty in view.All values are empty VisitingID, Description, Date Fields are empty and in Employee drop down it won't show the value which i passed to this field it shows the first value in dropdown. so please any one tell me how to solve this issue. Actually I try to explain my issue as per my level best and if you didn't understand my issue or any one need my full code or need more code tell me . i ready to update my code again. but i need solution.
Advance Thanks..
use:
#Html.DropDownListFor(model => model.EmployeeID,(IEnumerable<SelectListItem>)ViewData["EmployeeName"])
The important part being "DropDownListFor". You are using "DropDownList".
Use the DropDownListFor helper method.
#Html.DropDownListFor(model => model.EmployeeID,
(IEnumerable<SelectListItem>)ViewData["EmployeeName"])
Now in your GET action, you need to set the EmployeeID property value of your view model.
public ActionResult Edit(int id)
{
var objVisitorsviewModel = new VisitorsViewModel();
// I am hard coding to 25.
// You may replace it with a valid Employee Id from your db table for the record
ObjVisitorsviewModel.EmployeeID= 25;
return View(objVisitorsviewModel);
}
A more clean solution is to not use ViewData to transfer the data you need to render the dropdown option. You can make your code more strongly typed by simply adding a new property to your view model
public class VisitorsViewModel
{
public List<SelectListItem> Employees { set;get;}
public Guid? EmployeeID { get; set; }
// Your existing properties goes here
}
Now in your GET action(create/edit), Instead of storing the data in ViewData, we will load to the Empenter code hereloyees property.
public ActionResult Edit(int id)
{
var vm = new VisitorsViewModel();
vm.Employees = db.Employees.Select(s=> new SelectListItem {
Value=s.EmployeId.ToString(), Text=s.DisplayName }).ToList();
return View(vm);
}
And in your view, we will use the DropDownListFor helper method with the Employees property
#model VisitorsViewModel
#using(Html.BeginForm())
{
#Html.DropDownListFor(s=>s.EmployeeID,Model.Employees,"Select")
}
You are using a DropDownList(...) instead of a DropDownListFor(...)
Your Model
You must add a SelectList:
public SelectList Employees { get; set }
Your Edit
You must get your employees list and add it to your model:
// Get employees list from the database
var employees = db.Employee.Select(x => x.Id, x.Name).Tolist();
// Put the employees in a SelectList
var selectList = new SelectList(employees .Select(x => new { value = x.Id, text = x.Name }), "value", "text");}).ToList();
// Pass the list to your ViewModel
ObjVisitorsviewModel.Employees = selectList;
Your View
Finally, change your DropDownListFor line for this:
#Html.DropDownListFor(model => model.EmployeeID,
model.Employees)
By using DropDownList(...), your object data is not bound to the DropDown. You must manage its selected value manually.

How to display dynamic dropdownlists in Edit view with selected values in .NET MVC?

I have a form, which includes three dynamic dropdownlists. They are all one-to-many relationships. The first dropdownlist has loaded values and the other two are empty at the start. When user selects one value from the 1st dropdownlist, the 2nd dropdownlist will load corresponding items; when user selects a value from the 2nd dropdownlist, the 3rd dropdownlist will load relating items.
User can create the form and submit. My CreateController GET and POST methods works well.
Now I need EditController to allow user to edit his form. The problem is how to display the 2nd and the 3rd dynamic dropdownlist with selected values?
In my viewModel:
public Nullable<int> Tech_ID { get; set; }
public string TechniqueName { get; set; }
public SelectList Techniques { get; set; }
public Nullable<int> BU_ID { get; set; }
public string BuName { get; set; }
public SelectList BusinessUnits { get; set; }
In my Edit Controller:
ViewBag.Bulist = new SelectList(AllBus, "BU_ID", "BU_Title", form.BU_ID);
var butechList = GetTechList(Convert.ToInt32(form.BU_ID));
IEnumerable<SelectListItem> butechs = butechList.Select(m => new SelectListItem()
{
Value = m.Tech_ID.ToString(),
Text = m.Technique.Tech_Title
});
ViewBag.Techlist = new SelectList(butechs, "Tech_ID", "Tech_Title", form.Tech_ID);
in View page:
#Html.DropDownListFor(model => model.BU_ID,
new SelectList((IEnumerable<SelectListItem>)#ViewBag.Bulist, "Value", "Text", Model.BU_ID),
new { id = "ddlBU" })
#Html.DropDownListFor(model => model.Tech_ID,
new SelectList((IEnumerable<SelectListItem>)#ViewBag.Techlist, "Value", "Text", Model.Tech_ID),
new { id = "ddlTechs" })
The first dropdownlist is working correctly, but the second is not.
Firstly, you have a view model containing SelectList properties, so make use of it rather than using ViewBag properties.
Next, delete the unnecessary last parameter (object selectedValue) in you SelectList constructors - your binding to a property in your model so it is ignored (internally the DropDwonListFor() method generated a new IEnumerable<SelectListItem> and sets the selectedValue based on the value of the property your binding to)
But the main issue is that your unnecessarily generating 3 IEnumerable<SelectListItem>. The first using
IEnumerable<SelectListItem> butechs = butechList.Select(...
which is correct. Then you try and create another one form it using
ViewBag.Techlist = new SelectList(butechs, "Tech_ID", "Tech_Title", form.Tech_ID);
but this time it will throw an exception because butechs is IEnumerable<SelectListItem> and SelectListItem does not contain properties Tech_ID and Tech_Title (it would need to be new SelectList(butechs, "Value", "Text") to prevent the error, but its pointless so just delete it). And then you try to create a 3rd IEnumerable<SelectListItem> inside the DropDownListFor() method (again its pointless extra ovehead).
Your code in the controller simply needs to be
var butechList = GetTechList(form.BU_ID.Value); // its already an int!
model.Techniques = new SelectList(butechList, "Tech_ID", "Tech_Title");
return View(model);
and in the view
#Html.DropDownListFor(m => m.Tech_ID, Model.Techniques) // not sure why you would need to change the id from the default id="Tech_ID" to id="ddlBU"?
I also suggest you study the code in this DotNetFiddle which shows an example of generating cascading dropdownlists. In particular the code in the private void ConfigureViewModel(ViewModel model) method, which will generate the correct SelectList's based on selected values, and can be called from both the Create() and Edit() methods (both the GET and the POST if you need to return the view)

ASP.NET MVC 4 DropdownListFor, Populating using LINQ from DBContext?

Having a hard time finding answer to this question (Google, StackOverflow and ASP.NET).
// Model
public IEnumerable<SelectListItem> State { get; set; }
// View
#Html.DropDownListFor(m => m.State, ????)
// Controller
using (var dbcontext = MyDbContext()) {
// ??
}
return View(model);
I'm at a complete loss how to populate a mvc dropdownlistfor using LINQ from a DBContext. I understand the DBContext thing and have one setup. I'm not clear on how to construct a linq query and then pass that result (LIST?) to the DropDownListFor helper? Using MS SQL and I have a States table (id, name).
Firstly, in you model, include properties for what you want to bind to and the list of selections
public class MyViewModel
{
public string StateID { get; set; }
.... // other properties
public SelectList StateList { get; set; }
}
In the controller
// Initialise view model
MyViewModel model = new MyViewModel();
// Select the data to display (lots of ways to do this)
var states= from s in dbcontext.States
where s.SomeProperty == someValue // if you want to filer the results
select s
// Assign select list (this sets the value to the ID property and the display text to the Name property)
model.StateList = new SelectList(states, "ID", "Name");
// and if you want to set a default
model.StateID = "NY";
return View(model);
and in the view
#Html.DropDownListFor(m => m.StateID, Model.StateList)
this will display the full name of the states in the <select> and bind the states ID value to the property StateID
//dbcontext
using (var dbcontext = MyDbContext())
{
Dictionary<string, string> states = dbcontext .States.ToDictionary(t => t.StateID.ToString(), t => t.StateName.ToString());
}
// in controller attach this dictionary to ViewBag:
ViewBag.States=states;
// View
#Html.DropDownListFor(m => m.State, new SelectList(ViewBag.States, "Key", "Value"))

Categories

Resources