First of all please excuse my primitave knowlege of MVC4, Ill try to explain what im trying to achieve.
I am trying to build a simple pricing calculator for a website where by a user can input some data and select some predefined data that is served by the website.
In this instance, the website has a SQL database (lets call it my_portal) and a table called calculator. The calculator table has 4 fields, Id, device, device_name and unit.
The data which the user is able to enter is data and amount.
My model looks like the following;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;
using MyPortal.Models;
using System.ComponentModel.DataAnnotations;
namespace My_Portal.Models
{
public class Calculator
{
public int ID { get; set; }
public string device { get; set; }
public string sub_device { get; set; }
public string unit { get; set; }
}
public class TemporaryData
{
public int amount { get; set; }
public string type { get; set; }
public decimal data { get; set; }
public decimal result { get; set; }
}
}
public class CalculatorDBContext : DbContext
{
public DbSet<Calculator> Calculator { get; set; }
}
The controller is as follows;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using My_Portal.Models;
namespace My_Portal.Controllers
{
public class CalculatorController : Controller
{
private CalculatorDBContext db = new CalculatorDBContext();
//
// GET: /Calculator/
public ActionResult Index()
{
var db = new CalculatorDBContext();
var query = db.Calculator.Select(c => new { c.ID, c.device });
ViewBag.ID = new SelectList(query.AsEnumerable(), "ID", "device");
return View();
}
[HttpPost]
public ActionResult Index(TemporaryData calc)
{
calc.result = calc.amount + calc.data;
ViewData["Results"] = calc.result;
return View();
}
public ActionResult Overview()
{
return View(db.Calculator.ToList());
}
//
// GET: /Calculator/Details/5
public ActionResult Details(int id = 0)
{
Calculator calculator = db.Calculator.Find(id);
if (calculator == null)
{
return HttpNotFound();
}
return View(calculator);
}
//
// GET: /Calculator/Create
public ActionResult Create()
{
return View();
}
//
// POST: /Calculator/Create
[HttpPost]
public ActionResult Create(Calculator calculator)
{
if (ModelState.IsValid)
{
db.Calculator.Add(calculator);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(calculator);
}
//
// GET: /Calculator/Edit/5
public ActionResult Edit(int id = 0)
{
Calculator calculator = db.Calculator.Find(id);
if (calculator == null)
{
return HttpNotFound();
}
return View(calculator);
}
//
// POST: /Calculator/Edit/5
[HttpPost]
public ActionResult Edit(Calculator calculator)
{
if (ModelState.IsValid)
{
db.Entry(calculator).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(calculator);
}
//
// GET: /Calculator/Delete/5
public ActionResult Delete(int id = 0)
{
Calculator calculator = db.Calculator.Find(id);
if (calculator == null)
{
return HttpNotFound();
}
return View(calculator);
}
//
// POST: /Calculator/Delete/5
[HttpPost, ActionName("Delete")]
public ActionResult DeleteConfirmed(int id)
{
Calculator calculator = db.Calculator.Find(id);
db.Calculator.Remove(calculator);
db.SaveChanges();
return RedirectToAction("Index");
}
protected override void Dispose(bool disposing)
{
db.Dispose();
base.Dispose(disposing);
}
}
}
And finally the view;
@model My_Portal.Models.TemporaryData
@{
ViewBag.Title = "Index";
}
<h2>Calculator</h2>
@using (Html.BeginForm())
{
<fieldset>
<div class="display-label">
How many devices do you have?
</div>
<div class="display-field">
@Html.EditorFor(model => model.amount)
</div>
<div class="display-label">
How type of device do you have?
</div>
<div class="display-field">
@Html.DropDownList("ID", (IEnumerable<SelectListItem>) ViewBag.ID)
</div>
<div class="display-label">
How much data do you need to transfer?
</div>
<div class="display-field">
@Html.EditorFor(model => model.data)GB
</div>
@if (ViewData["Results"] != null)
{
<p>Estimated price for job is $@ViewData["Results"]</p>
}
<p>
<input type="submit" value="Calculate" />
</p>
</fieldset>
}
So im getting errors with the drop down list, namely "There is no ViewData item of type 'IEnumerable<SelectListItem>' that has the key 'ID'."
Putting this to one site, im still yet to find out how to pass the select vaule of the drop down list so I can perform calculation functions depending on what is selected using the unit information from the database.
Ive Googled and look at numerious tutorials, articles, examples, etc... and havent found something that is similar to what im trying to achieve.
Any help would be more appreciative.
Please keep in mind, im a very new MVC developer so be gentle :)
i think you should have ur SelectList defined in ur model, fill it in the controller and bind it in the view.. As m posting thru mobile so not able to provide any sample code, but I think thats the standard practice 4 binding ddl
Thanks for the information, although the logic you describe makes sence, im not sure how to actually code this, when you have time could you supply the code changes I would have to make?
Error 1 The call is ambiguous between the following methods or properties: 'System.Web.Mvc.Html.SelectExtensions.DropDownListFor<My_Portal.Models.Calculator,string>(System.Web.Mvc.HtmlHelper<My_Portal.Models.Calculator>, System.Linq.Expressions.Expression<System.Func<My_Portal.Models.Calculator,string>>, System.Collections.Generic.IEnumerable<System.Web.Mvc.SelectListItem>, string)' and 'System.Web.Mvc.Html.SelectExtensions.DropDownListFor<My_Portal.Models.Calculator,string>(System.Web.Mvc.HtmlHelper<My_Portal.Models.Calculator>, System.Linq.Expressions.Expression<System.Func<My_Portal.Models.Calculator,string>>, System.Collections.Generic.IEnumerable<System.Web.Mvc.SelectListItem>, System.Collections.Generic.IDictionary<string,object>)' c:\Users\user\Desktop\My_Portal\My_Portal\Views\Calculator\Index.cshtml 23 14 My_Portal
public static List<SelectListItem> StateList()
{
List<SelectListItem> stateList = new List<SelectListItem>()
{
new SelectListItem{ Value="",Text="--State--"},
new SelectListItem{ Value="AL",Text="Alabama"}};
return stateList;
}
2.ViewBag.statelist = new SelectList(StateList(), "Value", "Text");
I can see what your doing in that code, loading he variables from a predefined list which would sit in the model, but im my situation I need to load the data from an SQL database as stated in my original post.
Im able to load the data from the database into the list with no issues, the problem I have is when I post the page (i.e. I need to send the selected item to the post component of the Index controler method) which applies some processing, it throws this
problem (which I reportd in my first post);
"There is no ViewData item of type 'IEnumerable<SelectListItem>' that has the key 'ID'."
public ActionResult Index()
{
var db = new CalculatorDBContext();
var query = db.Calculator.Select(c => new { c.ID, c.device });
ViewBag.type = new SelectList(query.AsEnumerable(), "ID", "device");
return View();
}
But I still get this error;
There is no ViewData item of type 'IEnumerable<SelectListItem>' that has the key 'type'.
DJ_Mo_G
Member
7 Points
43 Posts
Drop Down List Hell
Jan 13, 2013 03:12 AM|LINK
Hi All,
First of all please excuse my primitave knowlege of MVC4, Ill try to explain what im trying to achieve.
I am trying to build a simple pricing calculator for a website where by a user can input some data and select some predefined data that is served by the website.
In this instance, the website has a SQL database (lets call it my_portal) and a table called calculator. The calculator table has 4 fields, Id, device, device_name and unit.
The data which the user is able to enter is data and amount.
My model looks like the following;
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Data.Entity; using MyPortal.Models; using System.ComponentModel.DataAnnotations; namespace My_Portal.Models { public class Calculator { public int ID { get; set; } public string device { get; set; } public string sub_device { get; set; } public string unit { get; set; } } public class TemporaryData { public int amount { get; set; } public string type { get; set; } public decimal data { get; set; } public decimal result { get; set; } } } public class CalculatorDBContext : DbContext { public DbSet<Calculator> Calculator { get; set; } }The controller is as follows;
using System; using System.Collections.Generic; using System.Data; using System.Data.Entity; using System.Linq; using System.Web; using System.Web.Mvc; using My_Portal.Models; namespace My_Portal.Controllers { public class CalculatorController : Controller { private CalculatorDBContext db = new CalculatorDBContext(); // // GET: /Calculator/ public ActionResult Index() { var db = new CalculatorDBContext(); var query = db.Calculator.Select(c => new { c.ID, c.device }); ViewBag.ID = new SelectList(query.AsEnumerable(), "ID", "device"); return View(); } [HttpPost] public ActionResult Index(TemporaryData calc) { calc.result = calc.amount + calc.data; ViewData["Results"] = calc.result; return View(); } public ActionResult Overview() { return View(db.Calculator.ToList()); } // // GET: /Calculator/Details/5 public ActionResult Details(int id = 0) { Calculator calculator = db.Calculator.Find(id); if (calculator == null) { return HttpNotFound(); } return View(calculator); } // // GET: /Calculator/Create public ActionResult Create() { return View(); } // // POST: /Calculator/Create [HttpPost] public ActionResult Create(Calculator calculator) { if (ModelState.IsValid) { db.Calculator.Add(calculator); db.SaveChanges(); return RedirectToAction("Index"); } return View(calculator); } // // GET: /Calculator/Edit/5 public ActionResult Edit(int id = 0) { Calculator calculator = db.Calculator.Find(id); if (calculator == null) { return HttpNotFound(); } return View(calculator); } // // POST: /Calculator/Edit/5 [HttpPost] public ActionResult Edit(Calculator calculator) { if (ModelState.IsValid) { db.Entry(calculator).State = EntityState.Modified; db.SaveChanges(); return RedirectToAction("Index"); } return View(calculator); } // // GET: /Calculator/Delete/5 public ActionResult Delete(int id = 0) { Calculator calculator = db.Calculator.Find(id); if (calculator == null) { return HttpNotFound(); } return View(calculator); } // // POST: /Calculator/Delete/5 [HttpPost, ActionName("Delete")] public ActionResult DeleteConfirmed(int id) { Calculator calculator = db.Calculator.Find(id); db.Calculator.Remove(calculator); db.SaveChanges(); return RedirectToAction("Index"); } protected override void Dispose(bool disposing) { db.Dispose(); base.Dispose(disposing); } } }And finally the view;
@model My_Portal.Models.TemporaryData @{ ViewBag.Title = "Index"; } <h2>Calculator</h2> @using (Html.BeginForm()) { <fieldset> <div class="display-label"> How many devices do you have? </div> <div class="display-field"> @Html.EditorFor(model => model.amount) </div> <div class="display-label"> How type of device do you have? </div> <div class="display-field"> @Html.DropDownList("ID", (IEnumerable<SelectListItem>) ViewBag.ID) </div> <div class="display-label"> How much data do you need to transfer? </div> <div class="display-field"> @Html.EditorFor(model => model.data)GB </div> @if (ViewData["Results"] != null) { <p>Estimated price for job is $@ViewData["Results"]</p> } <p> <input type="submit" value="Calculate" /> </p> </fieldset> }So im getting errors with the drop down list, namely "There is no ViewData item of type 'IEnumerable<SelectListItem>' that has the key 'ID'."
Putting this to one site, im still yet to find out how to pass the select vaule of the drop down list so I can perform calculation functions depending on what is selected using the unit information from the database.
Ive Googled and look at numerious tutorials, articles, examples, etc... and havent found something that is similar to what im trying to achieve.
Any help would be more appreciative.
Please keep in mind, im a very new MVC developer so be gentle :)
nirman.doshi
Participant
1521 Points
783 Posts
Re: Drop Down List Hell
Jan 13, 2013 05:04 AM|LINK
Software Developer
Vadodara, India
DJ_Mo_G
Member
7 Points
43 Posts
Re: Drop Down List Hell
Jan 13, 2013 05:08 AM|LINK
Hi Nirman,
Thanks for the information, although the logic you describe makes sence, im not sure how to actually code this, when you have time could you supply the code changes I would have to make?
Thanks in advance.
DJ_Mo_G
Member
7 Points
43 Posts
Re: Drop Down List Hell
Jan 14, 2013 09:04 AM|LINK
Sorry to double post, but is there anyone that can assist me with this query?
AshiqueAhamm...
Member
102 Points
21 Posts
Re: Drop Down List Hell
Jan 14, 2013 09:12 AM|LINK
try this
@Html.DropDownListFor(m => m.State, (SelectList)ViewBag.statelist,null);
DJ_Mo_G
Member
7 Points
43 Posts
Re: Drop Down List Hell
Jan 14, 2013 09:56 AM|LINK
I put this into the view;
But VS2012 throws this error;
AshiqueAhamm...
Member
102 Points
21 Posts
Re: Drop Down List Hell
Jan 14, 2013 10:37 AM|LINK
bind the drop downlist as follows
1.
public static List<SelectListItem> StateList()
{
List<SelectListItem> stateList = new List<SelectListItem>()
{
new SelectListItem{ Value="",Text="--State--"},
new SelectListItem{ Value="AL",Text="Alabama"}};
return stateList;
}
2.ViewBag.statelist = new SelectList(StateList(), "Value", "Text");
3. @Html.DropDownListFor(m => m.State, (SelectList)ViewBag.statelist,null);
DJ_Mo_G
Member
7 Points
43 Posts
Re: Drop Down List Hell
Jan 14, 2013 10:48 AM|LINK
Hi Ashique,
I can see what your doing in that code, loading he variables from a predefined list which would sit in the model, but im my situation I need to load the data from an SQL database as stated in my original post.
Im able to load the data from the database into the list with no issues, the problem I have is when I post the page (i.e. I need to send the selected item to the post component of the Index controler method) which applies some processing, it throws this problem (which I reportd in my first post);
AshiqueAhamm...
Member
102 Points
21 Posts
Re: Drop Down List Hell
Jan 14, 2013 11:06 AM|LINK
okei
mvc model binder maps html elements with class properties while posting so the name should be same.
the property name
public string type { get; set; }and the html element name
@Html.DropDownList("ID", (IEnumerable<SelectListItem>) ViewBag.ID)
are different
i mean instead of 'ID' u should give 'type'
@Html.DropDownList("type", (IEnumerable<SelectListItem>) ViewBag.ID)
please try this way
DJ_Mo_G
Member
7 Points
43 Posts
Re: Drop Down List Hell
Jan 15, 2013 07:24 AM|LINK
So I updated the view with the code you provided;
@Html.DropDownList("type", (IEnumerable<SelectListItem>) ViewBag.ID)And the model with;
public string type { get; set; }Lastly the controller;
public ActionResult Index() { var db = new CalculatorDBContext(); var query = db.Calculator.Select(c => new { c.ID, c.device }); ViewBag.type = new SelectList(query.AsEnumerable(), "ID", "device"); return View(); }But I still get this error;
Any thoughts?