ASP.NET MVC 'SelectListItem' has no key defined Error
I am using ASP.NET individual user accounts implementation and tried to add a DropDownList in the Register View so that the user can choose the city where he is from. I get the following error:
'SelectListItem' has no key defined. Define the key for this EntityType. SelectListItems: EntityType: EntitySet 'SelectListItems' is based on type 'SelectListItem' that has no keys defined.
In RegisterViewModel I added the following:
[Required(ErrorMessage = "Select City!")]
[Display(Name = "City")]
public int CityId { get; set; }
public List<SelectListItem> Cities { get; set; }
View:
<div class="form-group">
@Html.LabelFor(m => m.CityId, new { @class = "col-md-2 control-label" })
<div class="col-md-10">
@Html.DropDownList("CityId", Model.Cities, "Select city", new { @class = "form-control" })
</div>
</div>
Controller:
GET method:
public ActionResult Register()
{
var model = new RegisterViewModel();
model.Cities = new List<SelectListItem>();
SqlConnection con = //here is the connection string;
string query = "SELECT * FROM City";
con.Open();
try
{
SqlCommand com = new SqlCommand(query, con);
SqlDataReader reader = com.ExecuteReader();
while (reader.Read())
{
var city = new SelectListItem { Text = reader["Name"].ToString(), Value = reader["Id"].ToString() };
model.Cities.Add(city);
}
}
catch(Exception ex)
{
Response.Write("Eroare baza de date" + ex.Message);
}
finally
{
con.Close();
}
return View(model);
}
And finally, the POST method
public async Task<ActionResult> Register(RegisterViewModel model)
{
if (ModelState.IsValid)
{
model.Cities = new List<SelectListItem>();
int cityId = model.CityId;
var user = new ApplicationUser
{ UserName = model.UserName, Email = model.Email, CityId = cityId};
var result = await UserManager.CreateAsync(user, model.Password);
if (result.Succeeded)
{
await SignInManager.SignInAsync(user, isPersistent:false, rememberBrowser:false);
return RedirectToAction("Index", "Home");
}
AddErrors(result);
}
return View(model);
}
c# asp.net asp.net-mvc
add a comment |
I am using ASP.NET individual user accounts implementation and tried to add a DropDownList in the Register View so that the user can choose the city where he is from. I get the following error:
'SelectListItem' has no key defined. Define the key for this EntityType. SelectListItems: EntityType: EntitySet 'SelectListItems' is based on type 'SelectListItem' that has no keys defined.
In RegisterViewModel I added the following:
[Required(ErrorMessage = "Select City!")]
[Display(Name = "City")]
public int CityId { get; set; }
public List<SelectListItem> Cities { get; set; }
View:
<div class="form-group">
@Html.LabelFor(m => m.CityId, new { @class = "col-md-2 control-label" })
<div class="col-md-10">
@Html.DropDownList("CityId", Model.Cities, "Select city", new { @class = "form-control" })
</div>
</div>
Controller:
GET method:
public ActionResult Register()
{
var model = new RegisterViewModel();
model.Cities = new List<SelectListItem>();
SqlConnection con = //here is the connection string;
string query = "SELECT * FROM City";
con.Open();
try
{
SqlCommand com = new SqlCommand(query, con);
SqlDataReader reader = com.ExecuteReader();
while (reader.Read())
{
var city = new SelectListItem { Text = reader["Name"].ToString(), Value = reader["Id"].ToString() };
model.Cities.Add(city);
}
}
catch(Exception ex)
{
Response.Write("Eroare baza de date" + ex.Message);
}
finally
{
con.Close();
}
return View(model);
}
And finally, the POST method
public async Task<ActionResult> Register(RegisterViewModel model)
{
if (ModelState.IsValid)
{
model.Cities = new List<SelectListItem>();
int cityId = model.CityId;
var user = new ApplicationUser
{ UserName = model.UserName, Email = model.Email, CityId = cityId};
var result = await UserManager.CreateAsync(user, model.Password);
if (result.Succeeded)
{
await SignInManager.SignInAsync(user, isPersistent:false, rememberBrowser:false);
return RedirectToAction("Index", "Home");
}
AddErrors(result);
}
return View(model);
}
c# asp.net asp.net-mvc
Your code looks fine. When are you getting the error ? when you load the page ? (GET action) ?
– Shyju
Nov 22 at 18:38
after i complete the form and press the submit button
– AlexandraP
Nov 22 at 18:59
1
ifModelState.IsValid
returnsfalse
, you need to reloadmodel.Cities
collection before returning to the same view( which uses this collection to build the SELECT element).
– Shyju
Nov 22 at 19:18
I found the error, in IdentityModels inside the ApplicationUser class I added "public List<SelectListItem> Cities { get; set; }", which was incorrect
– AlexandraP
Nov 22 at 19:32
That is why you use view models :)
– Shyju
Nov 22 at 19:37
add a comment |
I am using ASP.NET individual user accounts implementation and tried to add a DropDownList in the Register View so that the user can choose the city where he is from. I get the following error:
'SelectListItem' has no key defined. Define the key for this EntityType. SelectListItems: EntityType: EntitySet 'SelectListItems' is based on type 'SelectListItem' that has no keys defined.
In RegisterViewModel I added the following:
[Required(ErrorMessage = "Select City!")]
[Display(Name = "City")]
public int CityId { get; set; }
public List<SelectListItem> Cities { get; set; }
View:
<div class="form-group">
@Html.LabelFor(m => m.CityId, new { @class = "col-md-2 control-label" })
<div class="col-md-10">
@Html.DropDownList("CityId", Model.Cities, "Select city", new { @class = "form-control" })
</div>
</div>
Controller:
GET method:
public ActionResult Register()
{
var model = new RegisterViewModel();
model.Cities = new List<SelectListItem>();
SqlConnection con = //here is the connection string;
string query = "SELECT * FROM City";
con.Open();
try
{
SqlCommand com = new SqlCommand(query, con);
SqlDataReader reader = com.ExecuteReader();
while (reader.Read())
{
var city = new SelectListItem { Text = reader["Name"].ToString(), Value = reader["Id"].ToString() };
model.Cities.Add(city);
}
}
catch(Exception ex)
{
Response.Write("Eroare baza de date" + ex.Message);
}
finally
{
con.Close();
}
return View(model);
}
And finally, the POST method
public async Task<ActionResult> Register(RegisterViewModel model)
{
if (ModelState.IsValid)
{
model.Cities = new List<SelectListItem>();
int cityId = model.CityId;
var user = new ApplicationUser
{ UserName = model.UserName, Email = model.Email, CityId = cityId};
var result = await UserManager.CreateAsync(user, model.Password);
if (result.Succeeded)
{
await SignInManager.SignInAsync(user, isPersistent:false, rememberBrowser:false);
return RedirectToAction("Index", "Home");
}
AddErrors(result);
}
return View(model);
}
c# asp.net asp.net-mvc
I am using ASP.NET individual user accounts implementation and tried to add a DropDownList in the Register View so that the user can choose the city where he is from. I get the following error:
'SelectListItem' has no key defined. Define the key for this EntityType. SelectListItems: EntityType: EntitySet 'SelectListItems' is based on type 'SelectListItem' that has no keys defined.
In RegisterViewModel I added the following:
[Required(ErrorMessage = "Select City!")]
[Display(Name = "City")]
public int CityId { get; set; }
public List<SelectListItem> Cities { get; set; }
View:
<div class="form-group">
@Html.LabelFor(m => m.CityId, new { @class = "col-md-2 control-label" })
<div class="col-md-10">
@Html.DropDownList("CityId", Model.Cities, "Select city", new { @class = "form-control" })
</div>
</div>
Controller:
GET method:
public ActionResult Register()
{
var model = new RegisterViewModel();
model.Cities = new List<SelectListItem>();
SqlConnection con = //here is the connection string;
string query = "SELECT * FROM City";
con.Open();
try
{
SqlCommand com = new SqlCommand(query, con);
SqlDataReader reader = com.ExecuteReader();
while (reader.Read())
{
var city = new SelectListItem { Text = reader["Name"].ToString(), Value = reader["Id"].ToString() };
model.Cities.Add(city);
}
}
catch(Exception ex)
{
Response.Write("Eroare baza de date" + ex.Message);
}
finally
{
con.Close();
}
return View(model);
}
And finally, the POST method
public async Task<ActionResult> Register(RegisterViewModel model)
{
if (ModelState.IsValid)
{
model.Cities = new List<SelectListItem>();
int cityId = model.CityId;
var user = new ApplicationUser
{ UserName = model.UserName, Email = model.Email, CityId = cityId};
var result = await UserManager.CreateAsync(user, model.Password);
if (result.Succeeded)
{
await SignInManager.SignInAsync(user, isPersistent:false, rememberBrowser:false);
return RedirectToAction("Index", "Home");
}
AddErrors(result);
}
return View(model);
}
c# asp.net asp.net-mvc
c# asp.net asp.net-mvc
edited Nov 23 at 6:30
user3559349
asked Nov 22 at 18:29
AlexandraP
74
74
Your code looks fine. When are you getting the error ? when you load the page ? (GET action) ?
– Shyju
Nov 22 at 18:38
after i complete the form and press the submit button
– AlexandraP
Nov 22 at 18:59
1
ifModelState.IsValid
returnsfalse
, you need to reloadmodel.Cities
collection before returning to the same view( which uses this collection to build the SELECT element).
– Shyju
Nov 22 at 19:18
I found the error, in IdentityModels inside the ApplicationUser class I added "public List<SelectListItem> Cities { get; set; }", which was incorrect
– AlexandraP
Nov 22 at 19:32
That is why you use view models :)
– Shyju
Nov 22 at 19:37
add a comment |
Your code looks fine. When are you getting the error ? when you load the page ? (GET action) ?
– Shyju
Nov 22 at 18:38
after i complete the form and press the submit button
– AlexandraP
Nov 22 at 18:59
1
ifModelState.IsValid
returnsfalse
, you need to reloadmodel.Cities
collection before returning to the same view( which uses this collection to build the SELECT element).
– Shyju
Nov 22 at 19:18
I found the error, in IdentityModels inside the ApplicationUser class I added "public List<SelectListItem> Cities { get; set; }", which was incorrect
– AlexandraP
Nov 22 at 19:32
That is why you use view models :)
– Shyju
Nov 22 at 19:37
Your code looks fine. When are you getting the error ? when you load the page ? (GET action) ?
– Shyju
Nov 22 at 18:38
Your code looks fine. When are you getting the error ? when you load the page ? (GET action) ?
– Shyju
Nov 22 at 18:38
after i complete the form and press the submit button
– AlexandraP
Nov 22 at 18:59
after i complete the form and press the submit button
– AlexandraP
Nov 22 at 18:59
1
1
if
ModelState.IsValid
returns false
, you need to reload model.Cities
collection before returning to the same view( which uses this collection to build the SELECT element).– Shyju
Nov 22 at 19:18
if
ModelState.IsValid
returns false
, you need to reload model.Cities
collection before returning to the same view( which uses this collection to build the SELECT element).– Shyju
Nov 22 at 19:18
I found the error, in IdentityModels inside the ApplicationUser class I added "public List<SelectListItem> Cities { get; set; }", which was incorrect
– AlexandraP
Nov 22 at 19:32
I found the error, in IdentityModels inside the ApplicationUser class I added "public List<SelectListItem> Cities { get; set; }", which was incorrect
– AlexandraP
Nov 22 at 19:32
That is why you use view models :)
– Shyju
Nov 22 at 19:37
That is why you use view models :)
– Shyju
Nov 22 at 19:37
add a comment |
1 Answer
1
active
oldest
votes
try using this
@Html.DropDownListFor(x=>x.CityId, Model.Cities, "Select city", new { @class = "form-control" })
instead of this
@Html.DropDownList("CityId", Model.Cities, "Select city", new { @class = "form-control"
})
add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53436480%2fasp-net-mvc-selectlistitem-has-no-key-defined-error%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
1 Answer
1
active
oldest
votes
1 Answer
1
active
oldest
votes
active
oldest
votes
active
oldest
votes
try using this
@Html.DropDownListFor(x=>x.CityId, Model.Cities, "Select city", new { @class = "form-control" })
instead of this
@Html.DropDownList("CityId", Model.Cities, "Select city", new { @class = "form-control"
})
add a comment |
try using this
@Html.DropDownListFor(x=>x.CityId, Model.Cities, "Select city", new { @class = "form-control" })
instead of this
@Html.DropDownList("CityId", Model.Cities, "Select city", new { @class = "form-control"
})
add a comment |
try using this
@Html.DropDownListFor(x=>x.CityId, Model.Cities, "Select city", new { @class = "form-control" })
instead of this
@Html.DropDownList("CityId", Model.Cities, "Select city", new { @class = "form-control"
})
try using this
@Html.DropDownListFor(x=>x.CityId, Model.Cities, "Select city", new { @class = "form-control" })
instead of this
@Html.DropDownList("CityId", Model.Cities, "Select city", new { @class = "form-control"
})
answered Nov 23 at 5:39
Yash Soni
47510
47510
add a comment |
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Some of your past answers have not been well-received, and you're in danger of being blocked from answering.
Please pay close attention to the following guidance:
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53436480%2fasp-net-mvc-selectlistitem-has-no-key-defined-error%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Your code looks fine. When are you getting the error ? when you load the page ? (GET action) ?
– Shyju
Nov 22 at 18:38
after i complete the form and press the submit button
– AlexandraP
Nov 22 at 18:59
1
if
ModelState.IsValid
returnsfalse
, you need to reloadmodel.Cities
collection before returning to the same view( which uses this collection to build the SELECT element).– Shyju
Nov 22 at 19:18
I found the error, in IdentityModels inside the ApplicationUser class I added "public List<SelectListItem> Cities { get; set; }", which was incorrect
– AlexandraP
Nov 22 at 19:32
That is why you use view models :)
– Shyju
Nov 22 at 19:37