Viewbag not properly working transfer the wrong data - asp.net-mvc

I am student. I am new to ASP.NET MVC and I google it and I tried see I write all code but viewbag not properly working
I am transferring data and using the viewing but not transferring the dropdown value
type.cs
public class Type
{
//public int Value { get; set; }
//public string Text { get; set; }
public int typeid { get; set; }
public string typename { get; set; }
}
public class TypeViewModel
{
//public List<Type> TypeDetaills { get; set; }
public SelectList TypeList { get; set; }
}
HomeControlle.cs
TypeViewModel TypeViewModel = new TypeViewModel();
public ActionResult Index()
{
SqlCommand cmd = new SqlCommand("getType", cn);
cmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
cn.Open();
da.Fill(ds);
DataTable dt = ds.Tables[0];
List<Type> objcountry = new List<Type>();
SelectList objlistofcountrytobind = new SelectList(dt.AsDataView(), "typeid", "typename", 0);
TypeViewModel.TypeList = objlistofcountrytobind;
ViewBag.typename = TypeViewModel.TypeList;
cn.Close();
return View();
}
[HttpPost]
public ActionResult CreateCustomer(Customer customer,string TypeList)
{
customer.Type = TypeList;
customer.CustomerName = cust;
return RedirectToAction("Index");
}
Index.cshtml
#model projectname.Models.TypeViewModel
#{
ViewBag.Title = "Index";
//var t = ViewBag.typename;
}
<h2>Type Query</h2>
#using (Html.BeginForm("CreateCustomer", "Home", FormMethod.Post, new { TypeList = #ViewBag.typename }))
{
<div class="form-group">
<div class="row">
<label>Type Name:</label>
#Html.DropDownListFor(model => model.TypeList, ViewBag.typename as SelectList)
#*#Html.Hidden("TypeList", #ViewBag.typename);*#
#*#Html.HiddenFor("TypeList", #ViewBag.typename);*#
#*#Html.HiddenFor(x => x.TypeList)*#
#*<input type="hidden" value="#ViewBag.typename" />*#
#*#Html.DropDownList("typeid", t as SelectList)*#
#*#Html.DropDownListFor(x => x.typename, new SelectList((IEnumerable<Type>)t, "typeid", "typename"))*#
</div>
</div>
<div class="form-group">
<div class="row">
<label>Customer Name:</label>
<input type="text" id="cust" name="cust" />
</div>
</div>
<input type="submit" />
}
see i select the runtime warranty from the drop down
I am trying to pass controller warranty not 2
see stored procedure getType fill this stored procedure in dropdown
I tried hiddenfor attribute but it not work
I want the pass warranty to createcustomer controller not 2
please help

Before trying to create code, you have to learn that the first letter in MVC is for model. So you have forget that viewbag is even exist. Create a view model , assign data and pass it from the action and use it inside of the view
TypeViewModel.TypeList = objlistofcountrytobind;
return View (TypeViewModel)
and you can only assign as a hidden (or not hidden) the primitive types (as string or int) not the whole instanse of the class

Pass text and value field same, if you want the text field to be posted back to the controller action method. By default dropdownlist uses value field.
Change that line!
SelectList objlistofcountrytobind = new SelectList(dt.AsDataView(), "typename", "typename", 0);

You can modify your view model as described in the following post: How to get DropDownList SelectedValue in Controller in MVC.
Or you can use the JavaScript:
#Html.DropDownListFor(model => model.TypeList,
ViewBag.type_name as SelectList,
new { onchange=" { var ddltext = $(`#TypeList option:selected`).text();$('#textvalue').val(ddltext);}" })
#Html.Hidden("typeList", "")
<script src="~/Scripts/jquery-3.3.1.min.js"></script>

Related

ASP.NET Core MVC - How to add other attributes from referenced table in drop-down in View

I'm using ASP.NET Core v3 MVC with Visual Studio 2019 Enterprise.
I have database like this:
I'm using database first approach to generate models for that database.
After that I'm adding following type of controller for product_info table:
Which will also generate Views. My question is - how can I display attributes from other tables in drop-down of Create View.
Here is example of what I mean:
I don't need complete solution, though it could be useful, any hints or pointers on how to do it would suffice.
You can create a viewmodel to display attributes in other model.
ViewModel:
public class ViewModel
{
public IEnumerable<SelectListItem> Model1Items{ get; set; }
public int SelectedId { get; set; }
}
Controller:
var items = (from m in db.Model1s
select new SelectListItem{
Value = m.Id,
Text = m.Name
}).ToList();
var vm = new ViewModel();
vm.Model1Items = new SelectList(items, "Value", "Text");
View:
#Html.DropDownListFor(model => model.SelectedId, Model.Model1Items, "--Select--")
This is full solution with fix for various problems I've encountered:
MODEL
Create folder in your project and call it ViewModel
Create class in that folder and call it ProductInfoViewModel.cs.Here is full content of ProductInfoViewModel.cs:
namespace ProductTest.ViewModels
{
public class ProductInfoViewModel
{
public int ProductId { get; set; }
public IEnumerable<SelectListItem> ProductName { get; set; } = new List<SelectListItem>();
public int CategoryId { get; set; }
public IEnumerable<SelectListItem> CategoryName { get; set; } = new List<SelectListItem>();
public int SubcategoryId { get; set; }
public IEnumerable<SelectListItem> SubcategoryName { get; set; } = new List<SelectListItem>();
}
}
Initialization with new List<SelectListItem>(); is important so you don't get NULL reference error.
CONTROLLER
Under // GET: ProductInfoes/Create add logic for getting data from database and loading it to ProductInfoViewModel object :
public IActionResult Create() {
// Hooks on databse to get list of Products
var products = (from m in _context.Product
select new SelectListItem
{
Value = m.ProductId.ToString(),
Text = m.ProductName
}).ToList();
// Create new instance of our ViewModels.ProductInfoViewModel(()
var vm = new ViewModels.ProductInfoViewModel();
// Fill in ProductName in ProductInfoViewModel with list fetch from database
vm.ProductName = new SelectList(products, "Value", "Text").Where(products => products != null);
// Do same thing to Category and Subcategory
var categories = (from m in _context.Category
select new SelectListItem{
Value = m.CategoryId.ToString(),
Text = m.CategoryName
}).ToList();
vm.CategoryName = new SelectList(categories, "Value", "Text").Where(categories => categories != null);
var subcategories = (from m in _context.Subcategory
select new SelectListItem
{
Value = m.SubcategoryId.ToString(),
Text = m.SubcategoryName
}).ToList();
vm.SubcategoryName = new SelectList(subcategories, "Value", "Text").Where(subcategories => subcategories != null);
//Pass that model to View
return View(vm);
}
VIEW
than go to Views/ProductInfoes/Create.cshtml file.
Add following code:
#model ProductTest.ViewModels.ProductInfoViewModel
#{
ViewData["Title"] = "Create";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h1>Create</h1>
<h4>ProductInfo</h4>
<hr />
<form asp-action="Create">
#Html.DropDownListFor(model => Model.ProductId, Model.ProductName, "--Select--")
#Html.DropDownListFor(model => Model.CategoryId, Model.CategoryName, "--Select--")
#Html.DropDownListFor(model => Model.SubcategoryId, Model.SubcategoryName, "--Select--")
<div class="form-group">
<input type="submit" value="Create" class="btn btn-primary" />
</div>
</form>
<div>
<a asp-action="Index">Back to List</a>
</div>
#section Scripts {
#{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}
If you go to your Create page, something like:
https://localhost:44382/ProductInfoes/Create
and you will get this:
Click Create after you choose from dropdown. And if you go back to index page you'll see that product is successfully added on the list.

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

Problem
I use the following code very similarily somewhere else in my application, but it is not working. I am completely stumped.
The ViewData item that has the key 'ShelfId' is of type 'System.Int32' but must be of type 'IEnumerable<SelectListItem>'
This is thrown during the post method. My model state is invalid.
Code
Models
Shelf
public class Shelf
{
[Key]
public int ShelfId
[Display(Name = "Shelf Id")]
[Required]
public string ShelfName
public virtual List<Book> Books {get; set;}
}
Book
public class Book
{
public int BookId
[Required]
[StrengthLength(160, MinimumLength = 8)]
public string BookName
public int ShelfId
public Shelf shelf {get; set;}
}
Controller
// GET: Units/Create
public async Task<IActionResult> Create()
{
var shelves = await _db.Shelves.OrderBy(q => q.Name).ToListAsync();
ViewBag.SelectedShelves = new SelectList(shelves, "ShelfId", "Name");
return View();
}
// POST: Units/Create
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create(Book book)
{
book.CreatedBy = User.Identity.GetUserName();
book.Created = DateTime.UtcNow;
book.UpdatedBy = User.Identity.GetUserName();
book.Updated = DateTime.UtcNow;
if (ModelState.IsValid)
{
db.Units.Add(unit);
await db.SaveChangesAsync();
return RedirectToAction("Index");
}
return View(book);
}
view
#model AgentInventory.Models.Book
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Create Unit</title>
</head>
<body>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal well bs-component" style="margin-top:20px">
<h4>Unit</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
<div class="control-label col-md-2">Room</div>
<div class="col-md-10">
#Html.DropDownListFor(model => model.ShelfId, (SelectList)ViewBag.SelectedShelves, "All", new { #class = "form-control" })
</div>
</div>
<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.BookName, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.BookName, "", new { #class = "text-danger" }
</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>
Attempts
I tried:
Adding #Html.HiddenFor(model=>model.ShelfId) in the create view, but that didn't work.
I have looked at similar issues on stackoverflow, but none of the fixes worked for me. (IE - hiddenfor, different kinds of selectlists)
Since I am new to MVC framework, I would be grateful for any assistance. I don't understand why this code works for two other kinds of models (Building and room), but not my current two models? It's weird.
PS - Is there a way to do this easily without using viewbag as well?
The reason for the error is that in the POST method when you return the view, the value of ViewBag.SelectedShelves is null because you have not set it (as you did in the get method. I recommend you refactor this in a private method that can be called from both the GET and POST methods
private void ConfigureViewModel(Book book)
{
var shelves = await _db.Shelves.OrderBy(q => q.Name).ToListAsync();
// Better to have a view model with a property for the SelectList
ViewBag.SelectedShelves = new SelectList(shelves, "ShelfId", "Name");
}
then in the controller
public async Task<IActionResult> Create()
{
// Always better to initialize a new object and pass to the view
Book model = new Book();
ConfigureViewModel(model)
return View(model);
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create(Book book)
{
if (!ModelState.IsValid)
{
ConfigureViewModel(book)
return View(book);
}
// No point setting these if the model is invalid
book.CreatedBy = User.Identity.GetUserName();
book.Created = DateTime.UtcNow;
book.UpdatedBy = User.Identity.GetUserName();
book.Updated = DateTime.UtcNow;
// Save and redirect
db.Units.Add(unit);
await db.SaveChangesAsync();
return RedirectToAction("Index");
}
Note your Book class contains only fields, not properties (no { get; set; }) so no properties will be set and the model will always be invalid because BookName has Required and StringLength attributes.
Also you have not shown all the properties in your model (for example you have CreatedBy, Created etc. and its likely that ModelState will also be invalid because you only generate controls for only a few properties. If any other properties contain validation attributes, then ModelState will be invalid. To handle this you need to create a view model containing only the properties you want to display edit.
public class BookVM
{
public int Id { get; set; }
[Required]
[StrengthLength(160, MinimumLength = 8)]
public string Name { get; set; }
public int SelectedShelf { get; set; }
public SelectList ShelfList { get; set; }
}
Then modify the private method to assign the SelectList to the view model (not ViewBag, and in the controller methods, pass a new instance of BookVM to the view, and post back to
public async Task<IActionResult> Create(BookVM model)
{
if (!ModelState.IsValid)
{
ConfigureViewModel(model)
return View(model);
}
// Initialize a new Book and set the properties from the view model
}

Retrieving values from partial view during post method

I have a view which contains a dropdown list and on dropdownlist item being selected I load a partial view. And when the form is submitted I want to be able to get both the values from main view and partial view during form submit.
Here is the main view
#model AdminPortal.Areas.Hardware.Models.CreateModule
#{
ViewBag.Title = "Create Module";
Layout = "~/Views/shared/_BootstrapLayout.basic.cshtml";
}
#Html.ValidationSummary(true)
<fieldset class="form-horizontal">
<legend>Add a Module <small>Create</small></legend>
#using (Html.BeginForm("CreateModule", "Module", new{id="AddModuleForm"}))
{
#Html.ValidationSummary(true)
<div class ="controls">
<div class="input-block-level">#Html.TextBoxFor(model => model.ModuleId, new {#placeholder = "ModuleID"})</div>
<br/>
<div class ="input-block-level" id="selectedModuleTypeName">#Html.DropDownListFor(model => model.SelectedModuleTypeName, Model.TypeNames,"Select Moduletype", new{id = "ModuleList"})</div>
<br/>
<div id="partialDiv"></div>
</div>
<div class="form-actions" id="buttons">
<button type="submit" class="btn btn-primary" id="Submit">Save changes</button>
#Html.ActionLink("Cancel", "ModuleList", null, new { #class = "btn " })
</div>
}
</fieldset>
<div>
#Html.ActionLink("Back to List", "ModuleList")
</div>
<script>
$("#buttons").hide();
$("#ModuleList").on("change", function() {
var modId = $(this).val();
$.get('#Url.Action("GetModulePropertyName", "Module")', { moduleTypeValue: modId }, function(result) {
$("#partialDiv").html(result);
});
//uncomment following section to check if the partial view is working properly
/*.done(function() { alert("done"); })
.fail(function() { alert("fail"); })
.always(function() { alert("completed"); });*/
});
$("#buttons").show();
</script>
and here is the partial view
#model IEnumerable<string>
#foreach(var names in Model)
{
<div class="input-block-level">#Html.TextBoxFor(m=>names, new{Value="", placeholder=names})</div>
<br/>
}
Here is my model
public class CreateModule
{
//Empty form to handle form serialization
public CreateModule()
{
}
[Required]
public string ModuleId { get; set; }
[DataType(DataType.DateTime)]
public DateTime DateEntered { get; set; }
[Required]
public string SelectedModuleTypeName { get; set; }
public IEnumerable<SelectListItem> TypeNames { get; set; }
public List<Property> Properties { get; set; }
}
public class Property
{
public string Name { get; set; }
public string Value { get; set; }
}
Here is the method that script in main view forwards to
[HttpGet]
public ActionResult GetModulePropertyName(string moduleTypeValue)
{
var moduleKindId = _repository.GetModuleKindId(moduleTypeValue);
var modulePropertyNames = _repository.GetModuleKindPropertyNames(moduleTypeValue);
return PartialView("GetModulePropertyName",modulePropertyNames);
}
and finally here is httppost method for the main view
[HttpPost]
public ActionResult CreateModule(CreateModule moduleV)
{
var module = new Module
{
ModuleTypeId = Convert.ToInt64(moduleV.SelectedModuleTypeName),
ModuleId = moduleV.ModuleId,
DateEntered = moduleV.DateEntered,
};
if (ModelState.IsValid)
{
_repository.AddModule(module);
Success("Module added successfully!");
return RedirectToAction("ModuleList", "Module", new {area = "Hardware"});
}
Error("Something went wrong!");
return RedirectToAction("CreateModule", "Module", new { area = "Hardware" });
}
Current situation:
When the form is posted, the properties value of the model that is being passed via partial view is null. I get other values, like typename, Module ID.
What I'd want:
I also want to get the value of properties that is being passed via partial view.
You don't have any input field for the Properties property anywhere in your form. So it will always be null. That's normal.
Here's how you could proceed. Start by setting the correct navigational property so that the helper generates correct names of the corresponding input fields.
Also make sure that you are passing an IEnumerable<Property> model to the partial if you want to be able to get them back correctly:
[HttpGet]
public ActionResult GetModulePropertyName(string moduleTypeValue)
{
var moduleKindId = _repository.GetModuleKindId(moduleTypeValue);
IList<Property> model = ...
return PartialView("GetModulePropertyName", model.ToList());
}
and in your partial view use an editor template:
#model IList<Property>
#{
// This indicates the current navigational context to the helpers
ViewData.TemplateInfo.HtmlFieldPrefix = "Properties";
}
#Html.EditorForModel()
and the last step is to define a custom editor template for the Property class: ~/Views/Shared/EditorTemplates/Property.cshtml (note that the name and location of the template is important)
#model Property
<div class="input-block-level">
#Html.HiddenFor(m => m.Name)
#Html.TextBoxFor(m => m.Value, new { placeholder = Model.Name })
</div>
<br />
Try using the
List<Property>
as a model in your partial view and pass the CreateModule.Properties as model from your View
The problem is model binder can not figure out there
#Html.TextBoxFor(m=>names, new{Value="", placeholder=names})
belongs to as the "names" is not a property on your model class. If you need to bind to the CreateModule.Properties you need to change the partial view to emit textboxes with aproprate names, like this one:
#model IEnumerable<string>
#
{
int i=0;
}
#foreach(var names in Model)
{
<div class="input-block-level">#Html.TextBox("Properties[" + i + "].Value")</div>
<br/>
}

Model returning null value

This is my code for my model
public class ManufacturerModel
{
public int ProductTYpeId { get; set; }
public int Id { get; set; }
public string Name { get; set; }
public List<SelectListItem> manf { get; set; }
public Manufacturer manufacturer { get; set; }
}
This is my code in cshtml file
#using (Html.BeginForm("addmanufacturer", "Admin", FormMethod.Post, new { id = "formPageID" }))
{
<div class="row">
<label>Select Existing Manufacturer<span style="color: Red">*</span>:</label>
<div class="formRight">
#Html.DropDownList("Id", Model.manf)
</div>
</div>
<div class="row">
<label>Manufacturer Name<span style="color: Red">*</span>:</label>
<div class="formRight">
#Html.TextBoxFor(m => m.manufacturer.name)
#Html.ValidationMessageFor(m => m.manufacturer.name)
</div>
</div>
}
I am posting this form and when I am trying to fetch the value from the manfacurer ie - ManufacturerModel manufacturer = new ManufacturerModel();
using a model object all the value are coming out null.
in the text box If I replace it with m => m.Name then I am able to get proper value of Name.
can any one suggest what the problem is
I am using the manf to bind a dropdown. If In case I post back the form and the if it is return the value becomes blank, I need to refill the value..
public ActionResult addmanufacturer(string id)
{
if (id == null)
id = "0";
ManufacturerModel manufacturer = new ManufacturerModel();
manufacturer.ProductTYpeId = Convert.ToInt32(id);
manufacturer.manf = GetManf();
manufacturer.Id = -1;
return View(manufacturer);
}
I think problem will be becouse of:
#using (Html.BeginForm("Action", "Controller", FormMethod, HTML ATTRIBUTES )) { }
You probably want this overload:
#using (Html.BeginForm("Action", "Controller", Route Values, FormMethod, html attributes )) { }
Important is say him that you want route values and not a html atrributes, so try this
#using (Html.BeginForm("addmanufacturer", "Admin", new { id = "formPageID" }, FormMethod.Post, null )) { }
Hope, it helps.
M.

If Scott Allen can make it work ... why can't I? Should be a simple drop down list - MVC3

I have been wrestling with what should be a very simple thing for weeks now. I simply want to create a dropdownlist in asp.net mvc 3 razor html page and I want the data for the dropdownlist to come from a model.
My Model is as follows which is in the Models.Project namespace.
public class Project
{
public Project()
{
CategoryId = 0;
Name = "";
Description = "";
//Categories = new Dictionary<int, string>();
Entities _db = new Entities(); //ef4
CateogoriesList = from c in _db.Categories
orderby c.Name
select c.Name;
}
public int CategoryId { get; set; }
[Required]
[DataType(DataType.Text)]
[Display(Name = "Project Name")]
public string Name { get; set; }
[Required]
[DataType(DataType.MultilineText)]
[Display(Name = "Project Description")]
public string Description { get; set; }
public IQueryable<string> CateogoriesList;
}
My Controller action is as follows
public ActionResult Create()
{
Models.Project.Project proj = new Models.Project.Project();
return View(proj);
}
My Razor view has the following relevant code ...
#{
ViewBag.Title = "Create";
Layout = "~/Views/Shared/_Layout.cshtml";
}
#model Models.Project.Project
#using (Html.BeginForm())
{
#Html.ValidationSummary(true);
<fieldset>
<legend>Submit Your Request</legend>
<div class="editor-label">#Html.LabelFor( Model => Model.CateogoriesList )</div>
<div class="editor-field">
#Html.DropDownList("Category", new SelectList( Model.CateogoriesList ) )
</div>
</fieldset>
<p><input type="submit" value="Send for RFP" /></p>
}
The problem is that I get the following error ...
Compiler Error Message: CS0135: 'Model' conflicts with the declaration 'System.Web.Mvc.WebViewPage<TModel>.Model'
I saw the following clip make it work with the ViewBag ... and I don't understand why it won't work when I include the list in the model.
http://www.pluralsight-training.net/microsoft/players/PSODPlayer.aspx?author=scott-allen&name=mvc3-building-data-i&mode=live&clip=0&course=aspdotnet-mvc3-intro
I have also seen that there are a lot of people that seem to have trouble with this simple task but in my googling ... I haven't come across anyone with the same error in trying to create a drop down list.
I would appreciate any suggestions that you or anyone may have. The only thing that I've come up with is that the SelectList constructor takes a parameter of type System.Collections.IEnumerable and what I'm trying to pass it is System.Collections.Generic.IEnumerable ... or something close to it ... and I don't know how to cast it appropriately ... though I don't think I should have to ... if it works with a viewbag as the means of transportation why doesn't it work with the model as the means of transportation?
Thanks,
EDIT:======================
The problem was to do with the type of object the selectList constructor would accept. For some reason it wouldn't accept a generic IQueryable but when I cast the result from the entity framework using the cast extension method toArray it suddenly worked.
So my model becomes ...
public class Project
{
public Project()
{
Riebro.RiebroEntities _db = new Riebro.RiebroEntities();
CategoriesList = (from c in _db.Categories
orderby c.Name
select c.Name).ToArray<string>();
}
[Display(Name = "Choose a category")]
public string[] CategoriesList;
}
note the .ToArray on the end of the query and then suddenly
#Html.DropDownList("Category", new SelectList(Model.CategoriesList))
works. Though I am going to point out the Model keyword here seems to be required.
In your view you use:
#model Models.Project.Project
whereas in your controller action you pass:
public ActionResult Create()
{
Riebro.Models.Project.Project proj = new Riebro.Models.Project.Project();
return View(proj);
}
Notice the difference? Models.Project.Project vs Riebro.Models.Project.Project. You don't seem to be using the same type on your controller as on your view.
Also notice that it is bad practice to use namespace names that contain the name of a class.
Another remark is about using the Model keyword in lambda expressions:
#Html.LabelFor(Model => Model.CateogoriesList)
You shouldn't use this keyword. Replace Model with something else.
See your code, what's that? that's the reason cause the error.
<div class="editor-label">#Html.LabelFor( Model => Model.CateogoriesList )</div>
correct one
<div class="editor-label">#Html.LabelFor( Model => Model.CategoryId )</div>
#using (Html.BeginForm())
{
#Html.ValidationSummary(true);
<fieldset>
<legend>Submit Your Request</legend>
<div class="editor-label">#Html.LabelFor(x=>x.CategoryId )</div>
<div class="editor-field">
#Html.DropDownList("Category", new SelectList(Model.CateogoriesList) )
</div>
</fieldset>
<p><input type="submit" value="Send for RFP" /></p>
}
Here is my simulation of your entity. I just add another CategoriesList2 which use to simulate the IQueryable object, but it's still working.
public class Project {
public Project() {
CategoryId = 0;
Name = "";
Description = "";
//Categories = new Dictionary<int, string>();
//Entities _db = new Entities(); //ef4
//CateogoriesList = from c in _db.Categories
// orderby c.Name
// select c.Name;
//IQueryable<string> categoriesList = (new string[] { }).AsQueryable();
CateogoriesList = new string[] { "abc", "def", "hij", "klm" };
CategoriesList2 = (new string[] { "abc", "def", "hij", "klm" }).AsQueryable();
}
public int CategoryId { get; set; }
[Required]
[DataType(DataType.Text)]
[Display(Name = "Project Name")]
public string Name { get; set; }
[Required]
[DataType(DataType.MultilineText)]
[Display(Name = "Project Description")]
public string Description { get; set; }
public string[] CateogoriesList;
public IQueryable<string> CategoriesList2;
}
Here is the view by using the IQueryable categories list
#model MvcApplication3.Models.Project
#using (Html.BeginForm())
{
#Html.ValidationSummary(true);
<fieldset>
<legend>Submit Your Request</legend>
<div class="editor-label">#Html.LabelFor(x=>x.CategoryId )</div>
<div class="editor-field">
#Html.DropDownList("Category", new SelectList(Model.CategoriesList2) )
</div>
</fieldset>
<p><input type="submit" value="Send for RFP" /></p>
}
You are using the reserved keyword Model in your lambda expression
<div class="editor-label">#Html.LabelFor( Model => Model.CateogoriesList )</div>
try this
<div class="editor-label">#Html.LabelFor( m=> m.CateogoriesList )</div>

Resources