How to create drop down list in Create.cshtml - c#

How to create drop down list in Create.cshtml, where the list is made of data from DB and if there is no such kind of data you want to choose you can enter new value and it saves in DB.
I tried to query from DB to a list and used ViewBag.DropDownList (it worked in Index.cshtml, but not in Create.cshtml, because I was getting error: There is no ViewData item of type 'IEnumerable' that has the key "MyDropDownList")
Create.cshtml:
#using LicenseManager.Models
#model LicenseManager.Models.CompanyNames
#{
ViewBag.Title = "Create";
}
<h2>Create</h2>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>CompanyNames</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.Name, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Name, new { htmlAttributes = new { #class = "form-control" } })
#Html.DropDownList("CompanyNames", (SelectList)ViewBag.DropDownValues)
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval") }
and controller CompanyNames.cs:
public class CompanyNamesController : Controller
{
private ApplicationDbContext db = new ApplicationDbContext();
// GET: CompanyNames
public ActionResult Index()
{
ApplicationDbContext db = new ApplicationDbContext();
var querys = from c in db.CompanyNames
select c.Name;
ViewBag.DropDownValues = new SelectList(querys);
return View(db.CompanyNames.ToList());
}
}
Can someone help me with this? I just need some kind of direction where to go, to do. Sorry for the code....

model created :
public class CustomerModel
{
public List<SelectListItem> ListAdCode { get; set; }
}
Create a function to bind a list :
public static List<SelectListItem> AdCodeList()
{
List<SelectListItem> list = new List<SelectListItem>();
list.Add(new SelectListItem { Text = "--Select--", Value = null, Selected = true });
using (CrmKolmEntities entities = new CrmKolmEntities())
{
var allActiveCAdCodes = entities.AdCodes.Where(x => x.IsDeleted == false).ToList();
if (allActiveCAdCodes.Count() > 0)
{
foreach (var adCode in allActiveCAdCodes)
{
list.Add(new SelectListItem { Text = adCode.AdCodeName, Value = adCode.AdCodeId.ToString() });
}
}
}
return list;
}
On Controller :
public ActionResult ManipulateCustomer(int id, int? idOrder)
{
CustomerModel model = new CustomerModel();
model.ListAdCode = AdCodeList();
if (model.ListPriceList == null)
{
model.ListPriceList = CommonFunctions.PriceListActive(null);
}
return View(model);
}
On View:
#Html.DropDownListFor(r => r.AdCodeId, new SelectList(Model.ListAdCode, "value", "text", "selectedValue"), new { #class = "input", #style = "width:450px" })

I think you need Html.DropDownList instead of ViewBag.DropDownList. The former is from the HtmlHelper class and I think it's what you need. You can read more about it here.

Related

How to list products by category in ASP.NET MVC?

I am trying to list a list of products by category value. The value of the category is the description of the product, if the product is an apple, the category will be Fruit. So I want the user to be able to choose the category, click a button, and list all the products with the same category. I'm trying do this, select category and list by category on a same View.
The model:
public partial class product
{
int id {get; set}
string name {get; set}
string category {get; set;}
}
The Controller:
[HttpGet]
public ActionResult ListByCat()
{
List<SelectListItem> lst = new List<SelectListItem>();
lst.Add(new SelectListItem() { Text = "Fruits", Value = "fruits" });
lst.Add(new SelectListItem() { Text = "Hardware", Value = "hardware"});
lst.Add(new SelectListItem() { Text = "Vegetables", Value = "vegetables"});
ViewBag.category = lst;
return View();
}
[HttpPost]
public ActionResult listByCat(product prod)
{
using (inventarioEntitiesDBA dc = new inventarioEntitiesDBA())
{
return View(dc.product.Where(a => a.category == prod.category).ToList());
}
}
And the view:
#model regMVC.Models.product
#{
ViewBag.Title = "listByCat";
}
<h2>listByCat</h2>
#using (Html.BeginForm())
{
<div class="form-group">
#Html.LabelFor(model => model.category, htmlAttributes: new { #class = "control- label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("category", null, htmlAttributes: new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.category, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="List by Category" class="btn btn-default" />
</div>
</div>
ViewModel
public class ListByCatViewModel
{
//This hold the selected value in post action
public string SelectedCategory { get; set; }
public List<SelectListItem> Categories { get; set; } = new List<SelectListItem>();
public List<Product> SearchResults { get; set; } = new List<Product>();
}
listByCat() GET Action, here we pass the ViewModel to the view
public ActionResult listByCat()
{
ListByCatViewModel listByCatViewModel = new ListByCatViewModel();
listByCatViewModel.Categories = buildCategories();
return View(listByCatViewModel);
}
Now the POST action, finding the result from the database, I am mocking the result from a list
[HttpPost]
public ActionResult listByCat(ListByCatViewModel listByCatViewModel)
{
if (ModelState.IsValid)
{
if (listByCatViewModel.SelectedCategory != null)
{
//Binding dropdown again
listByCatViewModel.Categories = buildCategories(listByCatViewModel.SelectedCategory);
var products = mockProductCollection();
var results = products.FindAll(x => x.category.ToLower() ==
listByCatViewModel.SelectedCategory.ToLower());
listByCatViewModel.SearchResults = results;
}
}
return View(listByCatViewModel);
}
My Helper method to fill Dropdownlist and Product list
private List<SelectListItem> buildCategories(string selectedItem = "")
{
List<SelectListItem> lst = new List<SelectListItem>();
lst.Add(new SelectListItem() { Text = "Fruits", Value = "fruits" });
lst.Add(new SelectListItem() { Text = "Hardware", Value = "hardware" });
lst.Add(new SelectListItem() { Text = "Vegetables", Value = "vegetables" });
if (!string.IsNullOrEmpty(selectedItem))
{
lst.Find(x => x.Value.ToLower() == selectedItem.ToLower()).Selected = true;
}
return lst;
}
private List<Product> mockProductCollection()
{
List<Product> products = new List<Product>() {
new Product(){id=1,category="fruits",name="Apple"},
new Product(){id=2,category="fruits",name="Banana"},
new Product(){id=3,category="hardware",name="Screws"},
new Product(){id=4,category="hardware",name="Bolt"},
new Product(){id=5,category="vegetables",name="Carrot"},
new Product(){id=6,category="vegetables",name="Cucumber"}
};
return products;
}
and finally the View
#model NETMVC.ViewModel.ListByCatViewModel
#{
ViewBag.Title = "Index";
}
<h2>Index</h2>
#using (Html.BeginForm())
{
<div class="form-group">
#Html.LabelFor(model => model.Categories, htmlAttributes: new { #class = "control- label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.SelectedCategory,Model.Categories, htmlAttributes: new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.Categories, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="List by Category" class="btn btn-default" />
</div>
</div>
}
#if (Model.SearchResults != null && Model.SearchResults.Count > 0)
{
<ul>
<li>Search Results</li>
#foreach (var product in Model.SearchResults)
{
<li>#product.name</li>
}
</ul>
}

populating dropdown menu from database in ASP.NET MVC [duplicate]

This question already has answers here:
Populating a razor dropdownlist from a List<object> in MVC
(9 answers)
Closed 3 years ago.
I have a view to create an 'Appointment' after choosing some options in 3 different drop-down menus (Patient, Doctor, Clinic)
I need help with creating and populating these 3 drop-down menus.
I'm pretty new to ASP.NET MVC and C#. So, your help is most appreciated.
I'll include the appointment controller and appointment creation view code.
AppointmentController
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ClinicManagement.Models;
namespace ClinicManagement.Controllers
{
public class AppointmentController : Controller
{
// GET: Appointment
public ActionResult Index()
{
using (HospitalDatabaseEntities DataBase = new HospitalDatabaseEntities())
{
return View(DataBase.Appointments.ToList());
}
}
// GET: Appointment/Details/5
public ActionResult Details(int id)
{
using (HospitalDatabaseEntities DataBase = new HospitalDatabaseEntities())
{
return View(DataBase.Appointments.Where(x => x.AppintID == id).FirstOrDefault());
}
}
// GET: Appointment/Create
public ActionResult Create()
{
return View();
}
// POST: Appointment/Create
[HttpPost]
public ActionResult Create(Appointment appointment)
{
try
{
using (HospitalDatabaseEntities DataBase = new HospitalDatabaseEntities())
{
DataBase.Appointments.Add(appointment);
DataBase.SaveChanges();
}
// TODO: Add insert logic here
return RedirectToAction("Index");
}
catch
{
return View();
}
}
// GET: Appointment/Edit/5
public ActionResult Edit(int id)
{
using (HospitalDatabaseEntities DataBase = new HospitalDatabaseEntities())
{
return View(DataBase.Appointments.Where(x => x.AppintID == id).FirstOrDefault());
}
}
// POST: Appointment/Edit/5
[HttpPost]
public ActionResult Edit(int id, Appointment appointment)
{
try
{
using (HospitalDatabaseEntities DataBase = new HospitalDatabaseEntities())
{
DataBase.Entry(appointment).State = EntityState.Modified;
DataBase.SaveChanges();
}
// TODO: Add update logic here
return RedirectToAction("Index");
}
catch
{
return View();
}
}
// GET: Appointment/Delete/5
public ActionResult Delete(int id)
{
using (HospitalDatabaseEntities DataBase = new HospitalDatabaseEntities())
{
return View(DataBase.Appointments.Where(x => x.AppintID == id).FirstOrDefault());
}
}
// POST: Appointment/Delete/5
[HttpPost]
public ActionResult Delete(int id, FormCollection collection)
{
try
{
// TODO: Add delete logic here
using (HospitalDatabaseEntities DataBase = new HospitalDatabaseEntities())
{
Appointment appointment = (DataBase.Appointments.Where(x => x.AppintID == id).FirstOrDefault());
DataBase.Appointments.Remove(appointment);
DataBase.SaveChanges();
}
return RedirectToAction("Index");
}
catch
{
return View();
}
}
}
}
Appointment 'Create' View
#model ClinicManagement.Models.Appointment
#{
ViewBag.Title = "Create";
}
<h2>Create</h2>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Appointment</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.DoctorID, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.DoctorID, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.DoctorID, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.PatientID, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.PatientID, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.PatientID, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.ClinicID, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.ClinicID, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.ClinicID, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Date, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Date, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Date, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create Appointment" class="btn btn-default" />
</div>
</div>
</div>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
If the drop down menu options are in a database, why not add a list to your model, populate that list in your GET ActionMethod and then render it using the DropdownListFor helper tag.
For example...
public class Appointment
{
public IEnumerable<SelectListItem> Clinic {get; set;}
//You should add this for every dropdown menu you intend to put in the list.
//I am guessing you already have a model like this as this was not in the question
}
public class Clinic
{
public int ClinicId {get; set;}
public string ClinicName {get; set;}
}
In the controller, you can then query the database for the options
public ActionResult Create()
{
var Clinic = context.Clinic.ToList();
var model = new Appointments()
{
Clinic = Clinic.Select(x => new SelectListItem
{
Value = x.ClinicId.ToString(),
Text = x.ClinicName
}
}
return View(model);
}
Like before, you would have to do this for all the fields. If you are worried about the numerous roundtrip to the database to get the values, do some research about Z.EntityFrameWork nuget pakages that lets you run batch SQL statements so you can get all three results with one database round trip.
Then in the view, you can do this...
#Html.DropDownListFor(m => m.ClinicId, Model.Clinic, "Select Clinic", new { #class = "form-control", id = "clinic" })
In Create controller GET , you should create 3 viewbag like
ViewBag.Patient = Database.Patient.ToList();
...
and in view, use dropdownlist:
#Html.DropDownList("PatientId", new SelectList(ViewBag.Accounts, "PatientId", "PatientName")), "choose the patient", new { #class = "form-control" }))

MVC how to update related navigation property

EDIT reformed my question based on #Stephen Muecke answer ..
it took me months trying to resolve such problem, but failed to.
my entities are:
public partial class Book
{
public int bookID { get; set; }
public string name { get; set; }
public string chapter { get; set; }
public virtual ICollection<Root> roots { get; set; }
}
.
public class Root
{
public int rootID { get; set; }
public string rooting { get; set; }
public virtual ICollection<Book> Book{ get; set; }
}
BooksController:
public class BooksController : Controller
{
private Context db = new Context();
// GET: Books
public ActionResult Index()
{
var boo = db.books.Include(x => x.roots).ToList();
List<RootyVM> model = new List<RootyVM>();
return View(boo);
}
....
....
// GET: Books/Create
public ActionResult Create()
{
return View();
}
// POST: Books/Create
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(IEnumerable<RootyVM> rootings, Book book)
{
if (ModelState.IsValid)
{
db.books.Add(book);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(book);
}
my view model RootyVM:
public class RootyVM
{
public int? rootID { get; set; }
[Required(ErrorMessage = "Please enter the name of the root!!")]
public string rooting { get; set; }
}
and my partial view _Rooting.cshtml
#model project.ViewModels.RootyVM
<div class="rooting">
#using (Html.BeginCollectionItem("rooting"))
{
#Html.HiddenFor(m => m.rootID, new { #class = "rootID" })
#Html.LabelFor(m => m.rooting)
#Html.TextBoxFor(m => m.rooting)
<button type="button" class="delete">Delete</button>
}
</div>
and my Razor view (Create.cshtml) as follows:
#model project.Models.Book
#{
ViewBag.Title = "Create";
}
<h2>Create</h2>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Book</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.name, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.name, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.name, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.chapter, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.chapter, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.chapter, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#using (Html.BeginForm())
{
<div id="rootings">
foreach(var rooting in Model)
{
#Html.Partial("_Rooting", rooting)
}
</div>
<button id="add" type="button">Add</button>
<input type="submit" value="Save" />
}
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
<div>
#Html.ActionLink("Back to List", "Index")
</div>
<script type="text/javascript">
var url = '#Url.Action("Rooting")';
var form = $('form');
var rootings = $('#rootings');
$('#add').click(function() {
$.get(url, function(response) {
rootings.append(response);
// Reparse the validator for client side validation
form.data('validator', null);
$.validator.unobtrusive.parse(form);
});
});
$('.delete').click(function() {
var container = $(this).closest('.rooting');
var id = container.find('.id').val();
if (id) {
// make ajax post to delete item
$.post(yourDeleteUrl, { id: id }, function(result) {
container.remove();
}.fail(function (result) {
// Oops, something went wrong (display error message?)
}
} else {
// It never existed, so just remove the container
container.remove();
}
});
</script>
}
HOWEVER, there is a mistake where i cannot find. Will appreciate your patience and help
ORIGINAL MAIN REQUESTS
however, I'm struggling in Create and Edit method. What I need to do is that:
Create a new book record and assign a root or more in the same view.
using dropdownlist is preferable.
if root doesn't exist, i want to add/create it on the fly, I mean immediately in the same create view.
I would appreciate if the Create view for relationship property i.e. Root is based on java where token are used (Select2).
I hope I made it clear for you to help me.

MVC Razor DropDownListFor value not set in model

I'm trying to make a razor view that can post a model to my controller.
I've added a dropdown, however platform is always null when i post to my controller.
What am i doing wrong?
This is my view
#using (Html.BeginForm("Register", "Home", FormMethod.Post, new { #class = "form-horizontal", #id = "form" }))
{
#{
var platformList = new List<SelectListItem>() {
new SelectListItem(){ Value="I", Text="iOS"},
new SelectListItem(){ Value="A", Text="Android"},
};
}
<div class="form-group">
#Html.LabelFor(model => model.platform, "Plattform", new { #for = "inputPlatform", #class = "col-lg-3 control-label" })
<div class="col-lg-9">
#Html.DropDownListFor(model => model.platform, platformList, new { #class = "form-control", #id = "inputPlatform" })
</div>
</div>
}
This is my model
public class RegistrationModel
{
public String platform { get; set; }
}
My Controller
[HttpPost]
[AllowAnonymous]
public ActionResult Register(RegistrationModel RegistrationModelViewModel)
{
}
I couldn't get your view to work. There appears to be a formatting issue with the drop down declaration. It has an extra comma and was missing a end }. I kept getting a parse error, which is odd as you say you can get the post to work.
Anyway, I've created an example below which works and so I hope is of some use.
Model
public class RegistrationModel
{
public string platform { get; set; }
}
View
#model TestMVC.Models.RegistrationModel
#using (Html.BeginForm("Register", "Register", FormMethod.Post, new { #class = "form-horizontal", #id = "form" }))
{
var platformList = new List<SelectListItem>() {new SelectListItem(){ Value="I", Text="iOS"}, new SelectListItem(){ Value="A", Text="Android"}};
<div class="form-group">
#Html.LabelFor(model => model.platform, "Plattform", new {#for = "inputPlatform", #class = "col-lg-3 control-label"})
<div class="col-lg-9">
#Html.DropDownListFor(model => model.platform, platformList, new {#class = "form-control", #id = "inputPlatform"})
</div>
</div>
<button type="submit"> Submit</button>
}
Controller
public class RegisterController : Controller
{
[HttpGet]
public ActionResult Register()
{
return View();
}
[HttpPost]
public ActionResult Register(RegistrationModel model)
{
//Do something here;
}
}

MVC auto validation

I am making my MVC application. I created a view, in which a user picks data from dropdown list. The view is like this:
#Scripts.Render("~/bundles/jquery")
#Scripts.Render("~/bundles/bootstrap")
#using ClassDeclarationsThsesis.Classes
#using Microsoft.Ajax.Utilities
#model ClassDeclarationsThsesis.Models.ClassesViewModel
#{ ViewBag.Title = "Classes";
}
<h2>Classes</h2>
#foreach (var user in Model.users)
{
if (user.email.Replace(" ", String.Empty) == HttpContext.Current.User.Identity.Name)
{
if (user.user_type.Replace(" ", String.Empty) == 3.ToString() || user.user_type.Replace(" ", String.Empty) == 2.ToString())
{
using (Html.BeginForm("Classes", "Account", FormMethod.Post, new { #class = "form-horizontal", role = "form" }))
{
#Html.AntiForgeryToken()
<h4>Generate summary views</h4>
<hr />
#Html.ValidationSummary("", new { #class = "text-danger" })
<div class="form-group">
#{
List<SelectListItem> listItems1 = new List<SelectListItem>();
}
#foreach (var subject in Model.subject)
{
listItems1.Add(new SelectListItem
{
Text = subject.name,
Value = subject.name,
});
}
#Html.LabelFor(m => m.subject_name, new { #class = "col-md-2 control-label" })
<div class="col-md-10">
#Html.DropDownListFor(m => m.subject_name, listItems1, new { #class = "form-control" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" class="btn btn-default" value="Submit" />
</div>
</div>
}
}
if (user.user_type.Replace(" ", String.Empty) == 1.ToString())
{
<p>You do not have enough permissions to enter this page. Contact the administrator.</p>
}
}
}
The controller is:
public ActionResult Classes()
{
ClassDeclarationsDBEntities1 entities = new ClassDeclarationsDBEntities1();
var model = new ClassesViewModel();
model.subject = entities.Subjects.ToList();
model.users = entities.Users.ToList();
if (ModelState.IsValid)
{
return RedirectToAction("ClassesPickGroup", "Account", new { subject_name=model.subject_name});
}
return View(model);
}
And the model:
public class ClassesViewModel
{
public List<Subject> subject { set; get; }
public List<User> users { get; set; }
[Required]
[Display(Name = "Subject")]
public string subject_name { get; set; }
}
But since the view only contains a single dropdown list, it is always Valid and redirects to different view straight away. How do I make the application wait for user choice in dropdown list and then submit the answer?
There is no problem in your view, but the problem that you create new object every time user submit and check for validation
public ActionResult Classes(ClassesViewModel model)
{
ClassDeclarationsDBEntities1 entities = new ClassDeclarationsDBEntities1();
if (ModelState.IsValid)
{
return RedirectToAction("ClassesPickGroup", "Account", new { subject_name=model.subject_name});
}
else {
model.subject = entities.Subjects.ToList();
model.users = entities.Users.ToList();
return View(model);
}
}

Categories

Resources