Render ViewModel errors on View if ModelState is not valid [duplicate] - c#

This question already has an answer here:
MVC model validation
(1 answer)
Closed 6 years ago.
I have a form like following in my MVC application:
#using (Html.BeginForm("Register", "User", FormMethod.Post))
{
<div>
#Html.TextBoxFor(m => m.FirstName, new { placeholder = "First name", #class = "form-control", #type = "text" })
</div>
<div>
#Html.TextBoxFor(m => m.LastName, new { placeholder = "Last name", #class = "form-control", #type = "text" })
</div>
<div>
#Html.TextBoxFor(m => m.Email, new { placeholder = "Email", #class = "form-control", #type = "email" })
</div>
<div>
#Html.TextBoxFor(m => m.Password, new { placeholder = "Password", #class = "form-control", #type = "password" })
</div>
<div>
#Html.TextBoxFor(m => m.PasswordConfirm, new { placeholder = "Confirm password", #class = "form-control", #type = "password" })
</div>
<div>
#Html.DropDownListFor(model => model.SelectedCountryId, Model.Countries, new { #class="select2_single form-control select2-hidden-accessible", #tabindex = "-1" })
</div>
<div>
<input class="btn btn-default submit" type="submit" value="Register" />
</div>
}
My ViewModel looks like following:
public class UserRegistrationViewModel
{
[Required(ErrorMessage = "First name is required!")]
public string FirstName { get; set; }
[Required(ErrorMessage = "Last name is required!")]
public string LastName { get; set; }
[Required(ErrorMessage = "Email name is required!")]
public string Email { get; set; }
[Required(ErrorMessage = "Password name is required!")]
public string Password { get; set; }
[Required(ErrorMessage = "Password confirmation name is required!")]
public string PasswordConfirm { get; set; }
public int SelectedCountryId { get; set; }
[Required(ErrorMessage = "Country needs to be selected!")]
public SelectList Countries { get; set; }
}
And these are my two actions:
public ActionResult Index()
{
var model = new UserRegistrationViewModel();
var countries = Connection.ctx.Countries.OrderBy(x => x.CountryName).ToList();
model.Countries = new SelectList(countries, "CountryId", "CountryName");
return View(model);
}
[HttpPost]
public ActionResult Register(UserRegistrationViewModel model)
{
if (ModelState.IsValid)
{
var user = new Users();
user.FirstName = model.FirstName;
user.LastName =model.LastName;
user.Email = model.Email;
user.PasswordSalt = Helpers.PasswordHelper.CreateSalt(40);
user.PasswordHash = Helpers.PasswordHelper.CreatePasswordHash(model.Password, user.PasswordSalt);
user.CountryId = Convert.ToInt32(model.SelectedCountryId);
user.Active = true;
Connection.ctx.Users.Add(user);
Connection.ctx.SaveChanges();
var role = new UserRoles();
role.RoleId = 2;
role.UserId = user.UserId;
role.Active = true;
user.UserRoles.Add(role);
Connection.ctx.SaveChanges();
return RedirectToAction("Index");
}
return null;
}
Now my question here is what do I do if the model state is not valid (ie. display the error messages that I've set up in my ViewModel)???
Do I just do `return View(); or ??
I need to render those messages on my view now...

Whenever I get an invalid form being submitted, I return the View() back for them to correct the issue. Taking them to an error page where they would have to come back to the form and start again would frustrate the user. Give them back the invalid form and tell them what needs correcting.
Now, what needs correcting can be read from the ViewBag(). Or you can have inside you Model some properties that will hold your error message for the user and display them if they are not null.

In the case of an invalid model state, you can just return the current view with the model as a parameter:
if (!ModelState.IsValid)
{
return View(model);
}
EDIT: In your html, add the html elements to show the validation messages:
#Html.ValidationMessageFor(model => model.FirstName)

Related

model validation error message isn't working And Returning Null

I have Model Based on DataBase and here it is
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated from a template.
//
// Manual changes to this file may cause unexpected behavior in your application.
// Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace Freelance.Models
{
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
public partial class User
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public User()
{
this.JobPosts = new HashSet<JobPost>();
this.Proposals = new HashSet<Proposal>();
this.Reviews = new HashSet<Review>();
this.SavedJobs = new HashSet<SavedJob>();
}
public int Id { get; set; }
[RegularExpression(#"^[\w-\.]+#([\w-]+\.)+[\w-]{2,4}$", ErrorMessage = "Email is not valid.")]
[Required(ErrorMessage = "Please enter Email"), MaxLength(50)]
public string Email { get; set; }
[Display(Name = "User Name")]
[Required(ErrorMessage = "Please enter User Name"), MaxLength(40)]
public string UserName { get; set; }
[Required(ErrorMessage = "Please enter Password"), MaxLength(50)]
public string Password { get; set; }
[Required(ErrorMessage = "Please enter First Name"), MaxLength(40)]
[Display(Name = "First Name")]
public string FirstName { get; set; }
[Required(ErrorMessage = "Please enter Last Name"), MaxLength(40)]
[Display(Name = "Last Name")]
public string LastName { get; set; }
[RegularExpression(#"\+(9[976]\d|8[987530]\d|6[987]\d|5[90]\d|42\d|3[875]\d|2[98654321]\d|9[8543210]|8[6421]|6[6543210]|5[87654321]|4[987654310]|3[9643210]|2[70]|7|1)\d{1,14}$", ErrorMessage = "Phone Number is not valid.")]
[Required, MaxLength(30)]
[Display(Name = "Phone Number")]
public string PhoneNumber { get; set; }
public string Photo { get; set; }
[Display(Name = "User Type")]
public string UserType { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<JobPost> JobPosts { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<Proposal> Proposals { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<Review> Reviews { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<SavedJob> SavedJobs { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<UserLogin> UserLogins { get; set; }
}
public partial class UserLogin
{
[RegularExpression(#"^[\w-\.]+#([\w-]+\.)+[\w-]{2,4}$", ErrorMessage = "Email is not valid.")]
[Required(ErrorMessage = "Please enter Email"), MaxLength(50)]
public string Email { get; set; }
[MinLength(8, ErrorMessage ="Password must be at least 8 length")]
[Required(ErrorMessage = "Please enter Password"), MaxLength(50)]
public string Password { get; set; }
}
}
i made the user login so i can login with only email and password because i can't send the User model because of the validation i put inside the class so i made UserLogin class
and here is my controller
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Login([Bind (Include ="Email,Password")]UserLogin user)
{
System.Diagnostics.Debug.WriteLine(user.Email);
System.Diagnostics.Debug.WriteLine(user.Password);
if (ModelState.IsValid)
{
System.Diagnostics.Debug.WriteLine("valid");
var data = db.Users.Where(u => u.Email.ToLower() == user.Email.ToLower() && u.Password == user.Password);
if (data.Count() == 1)
{
System.Diagnostics.Debug.WriteLine(data.SingleOrDefault().UserType);
FormsAuthentication.SetAuthCookie(data.SingleOrDefault().UserName.ToString(), true);
return RedirectToAction("CurrentUser");
}
}
ModelState.AddModelError("", "invalid Username or Password");
return RedirectToAction("Index", "Freelancer");
}
and here is the form in the view
#model Freelance.Models.ViewModels.HomeViewModel
#using (Html.BeginForm("Login", "User", FormMethod.Post))
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="mb-3">
<label for="LoginEmail" class="form-label">Email address</label>
#Html.EditorFor(u => u.user.Email, new { htmlAttributes = new { #class = "form-control", #id = "LoginEmail", #type = "Email", #required = "" } })
#Html.ValidationMessageFor(u => u.user.Email, "", new { #class = "text-danger" })
</div>
<div class="mb-3">
<label for="LoginPassword" class="form-label">Password</label>
#Html.EditorFor(u => u.user.Password, new { htmlAttributes = new { #class = "form-control", #id = "LoginPassword", #type = "Password", #required = "" } })
#Html.ValidationMessageFor(u => u.user.Password, "", new { #class = "text-danger" })
</div>
<div class="mb-3 form-check">
<input type="checkbox" onclick="ShowPassword()" class="form-check-input" id="ShowPasswordCheckBox">
<label class="form-check-label" for="ShowPasswordCheckBox">Show Password</label>
</div>
<div class="d-flex justify-content-center">
<button type="submit" class="btn btn-primary">Login</button>
</div>
}
iam using HomeViewModel so i can access different models in the same pages
public class HomeViewModel
{
public List<ViewModel> testModel { get; set; }
public List<JobPost> posts { get; set; }
public JobPost post { get; set; }
public List<User> users { get; set; }
public User user { get; set; }
public SavedJob savedPost { get; set; }
public List<SavedJob> savedPosts { get; set; }
}
the problem that when i try to submit the form it doesnot show error message even though i put
[MinLength(8)]
but in login method it does say that it's not valid model
my question here is why it doesnot show the error message in the html form ?
I did solve it as Serge Said
now here is my View :
#using (Html.BeginForm("Login", "User", FormMethod.Post))
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="mb-3">
<label for="LoginEmail" class="form-label">Email address</label>
#Html.EditorFor(u => u.userLogin.Email, new { htmlAttributes = new { #class = "form-control", #id = "LoginEmail", #type = "Email", #required = "" } })
#Html.ValidationMessageFor(u => u.userLogin.Email, "", new { #class = "text-danger" })
</div>
<div class="mb-3">
<label for="LoginPassword" class="form-label">Password</label>
#Html.EditorFor(u => u.userLogin.Password, new { htmlAttributes = new { #class = "form-control", #id = "LoginPassword", #type = "Password", #required = "" } })
#Html.ValidationMessageFor(u => u.userLogin.Password, "", new { #class = "text-danger" })
</div>
<div class="mb-3 form-check">
<input type="checkbox" onclick="ShowPassword()" class="form-check-input" id="ShowPasswordCheckBox">
<label class="form-check-label" for="ShowPasswordCheckBox">Show Password</label>
</div>
<div class="d-flex justify-content-center">
<button type="submit" class="btn btn-primary">Login</button>
</div>
}
It Returns null Values to The Controller
Since you have a special class for a login you have to add it your ViewModel
public class HomeViewModel
{
.....
public User user { get; set; }
public UserLogin userLogin { get; set; }
````
}
Fix your login view
<div class="mb-3">
<label for="LoginPassword" class="form-label">Password</label>
#Html.EditorFor(u => u.userLogin.Password, new { htmlAttributes = new { #class = "form-control", #id = "LoginPassword", #type = "Password", #required = "" } })
#Html.ValidationMessageFor(u => u.userLogin.Password, "", new { #class = "text-danger" })
</div>
and action too
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Login(HomeViewModel viewModel)
or maybe much better if you just use UserLogin as model in your login view
#model Freelance.Models.ViewModels.UserLogin
.....
<div class="mb-3">
<label for="LoginPassword" class="form-label">Password</label>
#Html.EditorFor(u => u.Password, new { htmlAttributes = new { #class = "form-control", #id = "LoginPassword", #type = "Password", #required = "" } })
#Html.ValidationMessageFor(u => u.Password, "", new { #class = "text-danger" })
</div>
you will have to change the action too
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Login(UserLogin userLogin)

How to populate Dropdown Values using Cosmos DB data on Register page C# MVC?

I am trying to display Dropdown list using Azure Cosmos db on Registration page form. But its not showing anything. I am new to C# MVC
I have created seperate model Customer to get client data from Azure. Passed it to View using Tempdata. But its just showing word "CustomerName" letters in dropdown. Please help, I am new to C#
namespace WebApplication1.Models
{
public class Customer
{
[JsonProperty(PropertyName = "id")]
public string Id { get; set; }
[JsonProperty(PropertyName = "Name")]
public string Name { get; set; }
[JsonProperty(PropertyName = "GroupId")]
public int GroupId { get; set; }
}
}
public class RegisterViewModel
{
[Required]
[EmailAddress]
[Display(Name = "Email")]
public string Email { get; set; }
[Required]
[StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
[DataType(DataType.Password)]
[Display(Name = "Password")]
public string Password { get; set; }
[DataType(DataType.Password)]
[Display(Name = "Confirm password")]
[Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
public string ConfirmPassword { get; set; }
[Required]
[Display(Name = "GroupId")]
public int GroupId { get; set; }
public Customer CustomerName { get; set; }
}
public async Task<ActionResult> Register(RegisterViewModel model)
{
if (ModelState.IsValid)
{
var user = new ApplicationUser { UserName = model.Email, Email = model.Email, GroupId = model.GroupId};
var item = await DocumentDBRepository<Customer>.GetCustomerAsync(d => d.Id != null);
TempData["item"] = item.ToList();
ViewBag.Id = item.Select(d =>d.GroupId);
ViewBag.Name = item.Select(d => d.Name);
var result = await UserManager.CreateAsync(user, model.Password);
if (result.Succeeded)
{
await SignInManager.SignInAsync(user, isPersistent:false, rememberBrowser:false);
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</a>");
return RedirectToAction("Landing", "Device");
}
AddErrors(result);
}
// If we got this far, something failed, redisplay form
return View(model);
}
#model WebApplication1.Models.RegisterViewModel
#using WebApplication1.Models;
#using System;
#{
ViewBag.Title = "Register";
}
<h2>#ViewBag.Title.</h2>
#{
var customerdata = (IEnumerable<Customer>)TempData["Customer"];
}
#using (Html.BeginForm("Register", "Account", FormMethod.Post, new { #class = "form-horizontal", role = "form" }))
{
#Html.AntiForgeryToken()
<h4>Create a new account.</h4>
<hr />
#Html.ValidationSummary("", new { #class = "text-danger" })
<div class="form-group">
<div class="col-md-10">
#Html.DropDownList("CustomerName", new SelectList(nameof(Model.CustomerName)), new { #class = "form-control" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(m => m.Email, new { #class = "col-md-2 control-label" })
<div class="col-md-10">
#Html.TextBoxFor(m => m.Email, new { #class = "form-control" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(m => m.Password, new { #class = "col-md-2 control-label" })
<div class="col-md-10">
#Html.PasswordFor(m => m.Password, new { #class = "form-control" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(m => m.ConfirmPassword, new { #class = "col-md-2 control-label" })
<div class="col-md-10">
#Html.PasswordFor(m => m.ConfirmPassword, new { #class = "form-control" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(m => m.GroupId, new { #class = "col-md-2 control-label" })
<div class="col-md-10">
#Html.TextBoxFor(m => m.GroupId, 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="Register" />
</div>
</div>
}
I am not getting any errors. But not getting required result as well. Dropdown is showing letters of "CustomerName" spelling in dropdown. Wheere I need Customer names in dropdown.
Instead of using the Tempdata use viewbag to bind deopdownlist
Here is the code that fetch data from item object and convert it into List<SelectListItem>
var item = await DocumentDBRepository<Customer>.GetCustomerAsync(d => d.Id != null);
TempData["item"] = item.ToList();
ViewBag.Id = item.Select(d =>d.GroupId);
ViewBag.Name = item.Select(d => d.Name);
List<SelectListItem> ddlcustomer = (from c in item
select new SelectListItem
{
Text = c.Name,
Value = c.GroupId,
}).ToList();
ViewBag.ddlcustomer = ddlcustomer;
View page
#Html.DropDownListFor("CustomerName", ViewBag.ddlcustomer as SelectList, new { #class = "form-control" })
I would suggest strongly type dropdownfor as you are passing your model from controller
#Html.DropDownListFor(model=>model.CustomerName.GroupId, ViewBag.ddlcustomer as SelectList, new { #class = "form-control" })

Invalid column name 'Length' webmatrix

im new in asp.net mvc. i watch a tutorial and he is using webmatrix. i tried to add column named "IDViewer" in table "UserProfile" in my database created by webmatrix. but then, when i tried to insert some value it returns me an error of "Invalid column name 'Length'." but i did not declare column name "Length" in my code. please check my codes and the images. thank you
Images Link Here. please take a look
The error
My database, i added column named IDViewer
public class Register
{
[Required(ErrorMessage = "Please provide password", AllowEmptyStrings = false)]
public string Username { get; set; }
[Required(ErrorMessage = "Please provide password", AllowEmptyStrings = false)]
[DataType(System.ComponentModel.DataAnnotations.DataType.Password)]
[StringLength(50, MinimumLength = 8, ErrorMessage = "Password must be 8 char long.")]
public string Password { get; set; }
public string IDViewer { get; set; }
}
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
#Html.ValidationSummary("", new { #style = "color: red" })
<label>Username</label>
#Html.TextBoxFor(m => m.Username, new { #class = "form-control" })
<label>Password</label>
#Html.PasswordFor(m => m.Password, new { #class = "form-control" })
<label>Student ID</label>
#Html.TextBoxFor(m => m.IDViewer, new { #class = "form-control" })
#Html.DropDownList("role",roles,"Select Account Type")
<button class="btn btn-primary">Register</button>
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Register(Register registerdata, string role)
{
if(ModelState.IsValid)
{
try
{
WebSecurity.CreateUserAndAccount(registerdata.Username, registerdata.Password, registerdata.IDViewer);
Roles.AddUserToRole(registerdata.Username,role);
return RedirectToAction("Index", "Home");
}
catch (MembershipCreateUserException)
{
ModelState.AddModelError("", "Sorry the username already exists");
return View(registerdata);
}
}
ModelState.AddModelError("","Data invalid");
return View(registerdata);
}
From the documentation, the 3rd parameter is a dictionary
propertyValues
Type: System.Object
(Optional) A dictionary that contains additional user attributes. The default is null.
so your method needs to be
WebSecurity.CreateUserAndAccount(registerdata.Username,
registerdata.Password, new { IDViewer = registerdata.IDViewer });

Checking if DropDownListFor item is selected in html

I have cshtml page like this:
<div class="form-group">
#Html.LabelFor(m => m.QuestionnaireName, new { #class = "col-md-2 control-label" })
#Html.DropDownListFor(m => m.QuestionnaireName, Model.Questionnaires, new { #id = "ddlQuestionnaires", #class = "form-control" })
#Html.Label("Questions list:", new { #class = "col-md-2 control-label" })
// here: how to check if any dropdownlistfor value is selected?
</div>
Like i said in comment above. I want to check if value of DropDownListFor is selected and in case yes, build dynamicaly (table or list) for element of chosen Questionnaire.
Let say that Questionnaire.name is unique id and Questionnaire contain List Questions.
here is my model:
public class FillQuestionnaireModel
{
[Required]
[DataType(DataType.Text)]
[Display(Name = "Select questionnaire")]
public string QuestionnaireName { get; set; }
public SelectList Questionnaires { get; set; }
}
and my controller actions:
public ActionResult Fill()
{
QuestionnaireServiceReference.QuestionnaireServiceClient client = new QuestionnaireServiceReference.QuestionnaireServiceClient();
FillQuestionnaireModel model = new FillQuestionnaireModel();
List<QuestionnaireServiceReference.Questionnaire> Questionnaires = client.GetAllQuestionnaires().ToList();
Questionnaires.Insert(0, new QuestionnaireServiceReference.Questionnaire() { questionnaire_id = 0, name = "--Select--" });
model.Questionnaires = new SelectList(Questionnaires, "name", "name");
return View(model);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Fill(FillQuestionnaireModel model)
{
if (!ModelState.IsValid)
{
string SelectedValue = model.QuestionnaireName;
return View(model);
}
else
{
QuestionnaireServiceReference.QuestionnaireServiceClient client = new QuestionnaireServiceReference.QuestionnaireServiceClient();
List<QuestionnaireServiceReference.Questionnaire> Questionnaires = client.GetAllQuestionnaires().ToList();
Questionnaires.Insert(0, new QuestionnaireServiceReference.Questionnaire() { questionnaire_id = 0, name = "--Select--" });
model.Questionnaires = new SelectList(Questionnaires, "name", "name");
}
return View(model);
}

changing a role with html select box asp.net mvc4

I am using the ASP.NET web application template and trying to allow a user to pick a role when registering.
Here is what I got at the moment.
Does it
View
<fieldset class="col-lg-5 .col-md-5">
<legend>Registration Form</legend>
<p>
#Html.LabelFor(m => m.UserName)
#Html.TextBoxFor(m => m.UserName, new { #class = "form-control" })
</p>
<p>
#Html.LabelFor(m => m.Password)
#Html.PasswordFor(m => m.Password, new { #class = "form-control" })
</p>
<p>
#Html.LabelFor(m => m.ConfirmPassword)
#Html.PasswordFor(m => m.ConfirmPassword, new { #class = "form-control" })
</p>
<p>
#Html.DropDownListFor(model => model.Type, Model.TypeList)
</p>
<input type="submit" value="Register" class="btn btn-default" />
</fieldset>
Model
public class RegisterModel
{
[Required]
[Display(Name = "User name")]
public string UserName { get; set; }
[Required]
[StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
[DataType(DataType.Password)]
[Display(Name = "Password")]
public string Password { get; set; }
[DataType(DataType.Password)]
[Display(Name = "Confirm password")]
[Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
public string ConfirmPassword { get; set; }
public string Type { get; set; }
public IEnumerable<SelectListItem> TypeList
{
get
{
return new List<SelectListItem>
{
new SelectListItem { Text = "athlete", Value = "athlete"},
new SelectListItem { Text = "coach", Value = "coach"},
};
}
}
}
Controller
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult Register(RegisterModel model)
{
if (ModelState.IsValid)
{
// Attempt to register the user
try
{
WebSecurity.CreateUserAndAccount(model.UserName, model.Password);
Roles.AddUserToRole(model.UserName, model.Type);
WebSecurity.Login(model.UserName, model.Password);
return RedirectToAction("Index", "Home");
}
catch (MembershipCreateUserException e)
{
ModelState.AddModelError("", ErrorCodeToString(e.StatusCode));
}
}
// If we got this far, something failed, redisplay form
return View(model);
}
I am feel like I am close but I can't quiet get it and i am getting this error
Compiler Error Message: Models.RegisterModel>' does not contain a definition for 'DropDownListFor' and the best extension method overload 'System.Web.Mvc.Html.SelectExtensions.DropDownListFor(System.Web.Mvc.HtmlHelper, System.Linq.Expressions.Expression>, System.Collections.Generic.IEnumerable)' has some invalid arguments
Did you initialize your model in HttpGet Register method? Like below...
[AllowAnonymous]
public ActionResult Register()
{
var model = new RegisterModel();
return View(model);
}
I create an empty template MVC4 app, added your code, got object reference not set error as default Register model does not pass model object to view which you are trying to access (i.e. loading TypeInt in DropDownListFor()).
I then initialized model in Get method as shown above. All works fine, i was able to pick a role on register view.
Check if this helps.
take a look your last comma should be removed:
new SelectListItem { Text = "athlete", Value = "athlete"},
new SelectListItem { Text = "coach", Value = "coach"}

Categories