changing a role with html select box asp.net mvc4 - c#

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"}

Related

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

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)

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 });

how to hold temporary value object in a actionresult and use it in another actionresult

hi i want to hold a temporary code eg."codes" in an actionmethod and use it on another actionmethod to compare if the model.code entered in the view textbox is"codes".But i dont want to save it to database
this is my first actionresult method which will hold the value
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> PhoneReset(ForgotPasswordView model, string sms)
{
if (ModelState.IsValid)
{
var user = await UserManager.FindByEmailAsync(model.Email);
// 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
if (user != null || user.PhoneNumber==model.cellNumber)
{
//string code = await UserManager.GeneratePasswordResetTokenAsync(user.Id);
//var forgot = new ForgotPasswordBusiness();
GenerateCodeBusiness gen = new GenerateCodeBusiness();
var codes = gen.CreateRandomPassword(8);
SendSmsBusiness objap = new SendSmsBusiness();
sms = "Your password reset code is " + codes;
objap.Send_SMS(model.cellNumber, sms);
await SignInAsync(user, isPersistent: false);
return RedirectToAction("ResetViaPhone", "Account");
}
else if (user == null)
{
ModelState.AddModelError("", "The user does not exist");
return View();
}
}
// If we got this far, something failed, redisplay form
return View(model);
}
this is the second actionresult
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> ResetPassword(ResetPasswordViewModel model)
{
if (!ModelState.IsValid)
{
return View(model);
}
var user = await UserManager.FindByNameAsync(model.Email);
if (user == null)
{
ModelState.AddModelError("", "No user found.");
return View();
}
IdentityResult result = await UserManager.ResetPasswordAsync(user.Id, model.Code, model.Password);
if (result.Succeeded)
{
return RedirectToAction("ResetPasswordConfirmation", "Account");
}
AddErrors(result);
return View();
}
this is the resetPassword view where the code is entered.
#model Template.Model.ResetPasswordViewModel
#{
ViewBag.Title = "Reset password";
}
<h2>#ViewBag.Title.</h2>
#using (Html.BeginForm("ResetPassword", "Account", FormMethod.Post, new { #class = "form-horizontal", role = "form" }))
{
#Html.AntiForgeryToken()
<h4>Reset your password.</h4>
<hr />
#Html.ValidationSummary("", new { #class = "text-danger" })
#Html.HiddenFor(model => model.Code)
<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">
<div class="col-md-offset-2 col-md-10">
<input type="submit" class="btn btn-default" value="Reset" />
</div>
</div>
}
this is the resetpassword model
public class ResetPasswordViewModel
{
[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; }
public string Code { get; set; }
any assistance will be of great help
Use TempData -
//Save values in tempData
TempData["codes"] = codes;
//Fetching the values in different action method
//Note: Cast the tempdata value to its respective type, as they are stored as object
var codes = TempData["codes"];
Please note that value in TempData will be available only till you fetch its value. Once fetched the value, it will be cleared.
The values in Tempdata are stored as objects, so you will need to cast the TemtData value to its respective type.
https://msdn.microsoft.com/en-in/library/dd394711%28v=vs.100%29.aspx

ASP.NET MVC Razor Model state not valid on RegisterModel

I'm having two issues with editing my applications RegisterModel.
A) The fields UserName and Email are rendered as password fields?
B) The modelstate is always invalid (and my model is empty)
I think they are both caused because I have a "HomeModel" which contains "LoginModel" and "RegisterModel" property and it passes the entire HomeModel instead of the corresponding property. How can I make it pass the correct one?
I have the following form:
#using (Ajax.BeginForm("Register", "Account", new AjaxOptions { UpdateTargetId = "RegisterAjaxResponse" }))
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
<div class="form-row">
<div id="RegisterAjaxResponse"></div>
</div>
<div class="form-row">
#Html.LabelFor(m => m.RegisterModel.UserName)
#Html.PasswordFor(m => m.RegisterModel.UserName)
#Html.ValidationMessageFor(m => m.RegisterModel.UserName)
</div>
<div class="form-row">
#Html.LabelFor(m => m.RegisterModel.Password)
#Html.PasswordFor(m => m.RegisterModel.Password)
#Html.ValidationMessageFor(m => m.RegisterModel.Password)
</div>
<div class="form-row">
#Html.LabelFor(m => m.RegisterModel.ConfirmPassword)
#Html.PasswordFor(m => m.RegisterModel.ConfirmPassword)
#Html.ValidationMessageFor(m => m.RegisterModel.ConfirmPassword)
</div>
<div class="form-row">
#Html.LabelFor(m => m.RegisterModel.Email)
#Html.PasswordFor(m => m.RegisterModel.Email)
#Html.ValidationMessageFor(m => m.RegisterModel.Email)
</div>
<div class="form-row">
<input type="submit" value='Register' />
</div>
}
The model:
public class RegisterModel
{
[Required]
[Display(Name = "User name")]
[DataType(DataType.Text)]
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; }
[Required]
[DataType(DataType.EmailAddress)]
[Display(Name = "EmailAddress")]
public string Email { get; set; }
}
But the UserName and Email field are rendered as an password field.
http://i.imgur.com/GCamint.png
-Can't page images yet, sorry.
And my modelstate is always invalid.
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult Register(RegisterModel model)
{
string returnValue = "";
if (ModelState.IsValid)
{
//Some code that is never executed
}
return Content(returnValue, "text/html");
}
Problem A: you're rendering the textfields for email and username using #Html.PasswordFor(), this will render password fields, try using #Html.TextboxFor()
And for problem B, it depends if you're targetting MVC3 or 4 and which version of .NET.
Later versions of .NET use the compare annotation as
[Compare(CompareField = Password, ErrorMessage = "Passwords do not
match")]
a) Because you have in razor view for them
#Html.PasswordFor(m => m.RegisterModel.UserName)
need to be
#Html.TextboxFor(m => m.RegisterModel.Email)

How does the MVC3 Controller retrieve HTTPPOST params?

I'm not quite understanding how this works.
Passing parameters from my entity objects works fine. But when I create new fields, only the first one is retrieved.
Model User Class:
public class User {
[Key]
public long Uid { get; set; }
[Required]
[StringLength(50, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 4)]
[DataType(DataType.EmailAddress)]
[Display(Name = "Email:")]
public string Email { get; set; }
[Required]
[StringLength(20, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 4)]
[Display(Name = "User Name:")]
public string Username { get; set; }
public string Password { get; set; }
public byte Role { get; set; }
public DateTime Created { get; set; }
}
CSHTML:
#using (Html.BeginForm( null,
null,
FormMethod.Post,
new { id = "regform" })
) {
#Html.ValidationSummary(true)
<fieldset>
<legend>Register</legend>
<div class="editor-label">
#Html.LabelFor(model => model.Email)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Email)
#Html.ValidationMessageFor(model => model.Email)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Username)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Username)
#Html.ValidationMessageFor(model => model.Username)
</div>
<div class="editor-label">
Password:
</div>
<div class="editor-field">
#Html.Password("pwd")
</div>
<div class="editor-label">
Confirm Password:
</div>
<div class="editor-field">
#Html.Password("confirm")
</div>
<p>
<input type="submit" value="Register" />
</p>
</fieldset>
}
Controller:
[HttpPost]
public ActionResult Register(User user, string pwd, string confirm) {
user.Username = confirm;
user.Created = DateTime.Now;
user.Role = 255;
user.Password = EncryptPassword.Password(pwd);
if (ModelState.IsValid && pwd == confirm) {
db.Users.Add(user);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(user);
}
Where I'm getting confused, is pwd picks up fine. confirm on the other hand remains null. My initial thought that it was calling by order and confirm in the model was simply conPwd. When that didn't work, I changed it's name to confirm. It still is not working and I can't find anything that explains how multiple parameters are passed to the controller.
Edit:
Updated my code. Believe it or not, this alone has taken me most of the day to write because I've been trying to understand what I'm doing. There is just so much to take in when you're learning Entities, LINQ, MVC, ASP.NET and Razor all at the same time. Basic C# is the only part I came in to this knowing. :)
You need a strongly typed view for your RegisterModel then use a Html.BeginForm to post the data to the controller.
Model
// This is the Model that you will use to register users
public class RegisterModel
{
[Required]
[Display(Name = "User name")]
public string UserName { get; set; }
[Required]
[DataType(DataType.EmailAddress)]
[Display(Name = "Email address")]
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; }
}
View (CSHTML)
// This is your strongly typed view that will use
// model binding to bind the properties of RegisterModel
// to the View.
#model Trainer.Models.RegisterModel
// You can find these scripts in default projects in Visual Studio, if you are
// not using VS, then you can still find them online
<script src="~/Scripts/jquery.validate.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
// This is where your form starts
// The "Account" parameter states what controller to post the form to
#using (Html.BeginForm((string)ViewBag.FormAction, "Account")) {
#Html.ValidationSummary(true, "Account creation was unsuccessful. Please correct the errors and try again.")
<fieldset>
<legend>Registration Form</legend>
<ol>
<li>
#Html.LabelFor(m => m.UserName)
#Html.TextBoxFor(m => m.UserName)
#Html.ValidationMessageFor(m => m.UserName)
</li>
<li>
#Html.LabelFor(m => m.Email)
#Html.TextBoxFor(m => m.Email)
#Html.ValidationMessageFor(m => m.Email)
</li>
<li>
#Html.LabelFor(m => m.Password)
#Html.PasswordFor(m => m.Password)
#Html.ValidationMessageFor(m => m.Password)
</li>
<li>
#Html.LabelFor(m => m.ConfirmPassword)
#Html.PasswordFor(m => m.ConfirmPassword)
#Html.ValidationMessageFor(m => m.ConfirmPassword)
</li>
</ol>
<!-- The value property being set to register tells the form
what method of the controller to post to -->
<input type="submit" value="Register" />
</fieldset>
}
Controller
// The AccountController has methods that only authorized
// users should be able to access. However, we can override
// this with another attribute for methods that anyone
// can access
[Authorize]
public class AccountController : Controller
{
// This will allow the View to be rendered
[AllowAnonymous]
public ActionResult Register()
{
return ContextDependentView();
}
// This is one of the methods that anyone can access
// Your Html.BeginForm will post to this method and
// process what you posted.
[AllowAnonymous]
[HttpPost]
public ActionResult Register(RegisterModel model)
{
// If all of the information in the model is valid
if (ModelState.IsValid)
{
// Attempt to register the user
MembershipCreateStatus createStatus;
Membership.CreateUser(model.UserName, model.Password, model.Email, passwordQuestion: null, passwordAnswer: null, isApproved: true, providerUserKey: null, status: out createStatus);
// If the out parameter createStatus gives us a successful code
// Log the user in
if (createStatus == MembershipCreateStatus.Success)
{
FormsAuthentication.SetAuthCookie(model.UserName, createPersistentCookie: false);
return RedirectToAction("Index", "Home");
}
else // If the out parameter fails
{
ModelState.AddModelError("", ErrorCodeToString(createStatus));
}
}
// If we got this far, something failed, redisplay form
return View(model);
}
}

Categories