Click here to Skip to main content
15,892,059 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
Quote:
An exception of type 'System.InvalidOperationException' occurred in System.Web.Mvc.dll but was not handled in user code Additional information: There is no ViewData item of type 'IEnumerable<selectlistitem>' that has the key 'State'.


here is my controller :-

using ebpassprojects.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ebpassprojects;
using System.Data.Entity;


namespace ebpassprojects.Controllers
{
    public class ListController : Controller
    {
        // GET: List

        private ApplicationDbContext db = new ApplicationDbContext();
        private void PopulateLookups(ApplicationDbContext db)
        {
            IEnumerable<SelectListItem> item = db.allofcity.Select(C => new SelectListItem
            {
                Value = C.cities,
                Text = C.cities
            }).ToList();

            ViewBag.city= item;

            IEnumerable<SelectListItem> item = db.allofstate.Select(C => new SelectListItem
            {
                Value = C.States,
                Text = C.States
            }).ToList();

            ViewBag.state = item;
        }


    }
}



and my view :-

<div class="form-group">
               @Html.LabelFor(m => m.State, new { @class = "col-md-2 control-label" })
               <div class="col-md-10">
                   @Html.DropDownListFor(m => m.State, (IEnumerable<SelectListItem>)ViewBag.state, "Select College", new { @class = "form-control" })
               </div>
           </div>
           <div class="form-group">
               @Html.LabelFor(m => m.City, new { @class = "col-md-2 control-label" })
               <div class="col-md-10">
                   @Html.DropDownListFor(m => m.City, (IEnumerable<SelectListItem>)ViewBag.city, "Select College", new { @class = "form-control" })
               </div>
           </div>


What I have tried:

i have tried viewdata instead of viewbag but its still not showing
Posted
Updated 12-Jun-20 6:16am
v2

Your code seem ok, very likely, like @Graeme_Grant had pointed out, the code is missing "State" attribute/property from the Model. Here a quick test/example. I'm assuming PopulateLookups method is functioning, which I think it is.

1. Create a very simple class, let call it TestState
C#
public class TestState
    {
        public string State { get; set; }
    }

2. Pick a controller/action, in my case, I picked home/Index
C#
public ActionResult Index()
        {
            PopulateLookups(db);
  
            return View();
        }

3. In the Index View, add the Model on the top and the dropdown below it
C#
@model WebApplication4.Models.TestState

<div class="form-group">
        @Html.LabelFor(m => m.State, new { @class = "col-md-2 control-label" })
        <div class="col-md-10">
            @Html.DropDownListFor(m => m.State, (IEnumerable<SelectListItem>)ViewBag.state, new { @class = "form-control" })
        </div>
    </div>

4. Run the application, navigate to home/index, you should see the dropdownlist with State in it.

5. If #4 work that proof your current Model is missing a property, add a State property in your Model that being referenced in the view. If that still doesn't work, post more code, share the model/view//controller with us again/
 
Share this answer
 
Comments
Himanshu.A.Joshi 5-Mar-17 13:56pm    
i want to bind this dropdownlist in my register page

here is my controller

i dont know where i put this

i tried one way but when i run it it shows me login page not regitration

here is my controller of registration page how to bind drpodownlist here

// GET: /Account/Register
[AllowAnonymous]
public ActionResult Register()
{


return View();
}

//
// POST: /Account/Register
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<actionresult> Register(RegisterViewModel model)
{
if (ModelState.IsValid)
{
var user = new ApplicationUser { UserName = model.Email, Email = model.Email };
var result = await UserManager.CreateAsync(user, model.Password);
using (ApplicationDbContext db = new ApplicationDbContext())

if (result.Succeeded)
{
await SignInManager.SignInAsync(user, isPersistent:false, rememberBrowser:false);

// For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771
// Send an email with this link
// string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);
// var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
// await UserManager.SendEmailAsync(user.Id, "Confirm your account", "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here");

return RedirectToAction("Index", "Home");
}
AddErrors(result);
}

// If we got this far, something failed, redisplay form
return View(model);
}
Bryian Tan 5-Mar-17 14:15pm    
Ok,
1. Where is the code calling the PopulateLookups to set the Viewbag? I didn't see it in Register() and Register(RegisterViewModel model)
2. Is there a State property in RegisterViewModel ?
Himanshu.A.Joshi 5-Mar-17 14:17pm    
thanks for your helps , i just solved that problem
C#
IEnumerable<SelectListItem> itenn = ...
ViewBag.state = itenn;
Spelling error.. itenn should beitem

Also, you have changed the property from State to Value & Text (?) here:
C#
Enumerable<SelectListItem> itenn = db.allofstate.Select(C => new SelectListItem
            {
                Value = C.States,
                Text = C.States
            }).ToList();
 
Share this answer
 
v3
Comments
Himanshu.A.Joshi 5-Mar-17 9:25am    
i have done what you said but still getting same error
Graeme_Grant 5-Mar-17 9:32am    
Yes, I can see that. The view is trying to access a model, not a ViewBag value.

You are using:
ViewBag.state = itenn;
when you should be using:
return View(item);
- this passes the model to the view.
Himanshu.A.Joshi 5-Mar-17 9:39am    
when i use
return View(item);

it say since 'listcontroller.populatelookups(ApplicationdbContext) retuns void, a return keyword must not be followed by an object expression
Graeme_Grant 5-Mar-17 9:49am    
Did you try googling the error message like I just did? return keyword must not be followed by an object expression - Google Search[^]

Yes, this is why:Hide   Copy Code
private void PopulateLookups(ApplicationDbContext db)
I am answering you inbetween compiles and running tests against code... I have given you plenty of information to fix it, you just need to do the work now.
Himanshu.A.Joshi 5-Mar-17 10:09am    
ya i have tried many things searched on google

i have tried this method

[HttpGet]
public ActionResult register(allstate t)
{
using (ApplicationDbContext db = new ApplicationDbContext())
{
ViewBag.state = db.allofstate.Select(C => new SelectListItem
{
Value = C.States,
Text = C.States
}).ToList();
}

return View();
}


but still getting same error
Posting this working example, from a previous Q&A support session. Principle is still the same:

1. Data Model:
C#
public class DataModel
{
    public Queue<List<string>> Data { get; set; } 
        = new Queue<List<string>>();
}
2. Controller
C#
public class HomeController : Controller
{
    public ActionResult Index()
    {
        var results = new DataModel();
        for (int i = 0; i < 10; i++)
        {
            results.Data.Enqueue(new List<string>() { "aaa", "bbb", "ccc" });
        }
        return View(results.Data);
    }
}
2. View
Razor
@{
    ViewBag.Title = "Queue Data Test";
}
@Model = IEnumerable<List<string>>;
<div>
    @foreach (var item in Model)
    {
        <p> data: 
        @string.Join(", ", item);
        </p>
    }
</div>
 
Share this answer
 
Comments
Himanshu.A.Joshi 5-Mar-17 11:11am    
it seems difficult i need to change my model, then all thing will going to messdup and the method you are giving is complex thanks for helping me but , i will find solution some how,,,, well thanksss
Graeme_Grant 5-Mar-17 12:06pm    
This is basic MVC programming. There is nothing complicated with the example. In the controller, I fill a model's property with values and then pass it to the view. The view then declares the model (enabling Intellisense and compiler validation) and iterates over the collection to display the values.

Start a new project, add the code and run it. Use breakpoints with the debugger and step through the code to see how it works.
Himanshu.A.Joshi 5-Mar-17 12:11pm    
done i got the solution , of my above problem

look what i have done

instead of using IEnumerable<selectlistitem> i have used

simple select list procedure

and in view also i have changed it to

@Html.DropDownListFor(m => m.States, (List<selectlistitem>)ViewBag.state, "Select state", new { @class = "form-control" })


now i am getting all states...finally
Graeme_Grant 5-Mar-17 12:18pm    
Boxing[^] (List<selectlistitem>)ViewBag.state has an expensive overhead and is not advisable for websites... Google SEO judges you for every millisecond that your page takes to load. That is why I passed a Strong Type[^].
Graeme_Grant 5-Mar-17 12:21pm    

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900