how to fix EntityValidationErrors - asp.net-mvc

I want to update user but whene I click on submit I get this error : EntityValidationErrors in this ligne :
Ligne 335 : context.SaveChanges();
I am using Entity Framework in ASP.NET MVC project:
this this my edit action in controller :
// GET: ApplicationUsers/Edit/2 :
[AuthLog(Roles = "Super Administrateur")]
public ActionResult Edit(string id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
ApplicationUser user = context.Users.Find(id);
if (user == null)
{
return HttpNotFound();
}
return View(user);
}
// POST: ApplicationUsers/Edit/2
[AuthLog(Roles = "Super Administrateur")]
[HttpPost, ValidateInput(false), ActionName("Edit")]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "Id,No_,RaisonSociale,Magasin,RemiseHabituelle,FamilyName,FirstName,EmailSup,Login,AffPrix,PasserCmd,EmailRespMagasin,Admin,BoursePR,Actif,IdSession,VendeurItirénant,ChargeClient,ValidOuAnnul,Email,EmailConfirmed,PasswordHash,SecurityStamp,PhoneNumber,PhoneNumberConfirmed,TwoFactorEnabled,LockoutEndDateUtc,LockoutEnabled,AccessFailedCount,UserName")] ApplicationUser applicationUser)
{
if (ModelState.IsValid)
{
context.Entry(applicationUser).State = EntityState.Modified;
context.SaveChanges();
return RedirectToAction("ListUsers","Account");
}
return View(applicationUser);
}
this is the Edit View :
<div class="form-horizontal">
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
#Html.HiddenFor(model => model.Id)
<div class="form-group">
#Html.LabelFor(model => model.Login, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Login, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Login, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Enregistrer" class="btn btn-default" />
</div>
</div>
</div>
}

The solution was : that UserName attributes is required.I find this error by adding block try {} catch {} to my edit action :
public ActionResult Edit([Bind(Include = "Id,No_,RaisonSociale,Magasin,RemiseHabituelle,FamilyName,FirstName,EmailSup,Login,AffPrix,PasserCmd,EmailRespMagasin,Admin,BoursePR,Actif,IdSession,VendeurItirénant,ChargeClient,ValidOuAnnul,Email,EmailConfirmed,PasswordHash,SecurityStamp,PhoneNumber,PhoneNumberConfirmed,TwoFactorEnabled,LockoutEndDateUtc,LockoutEnabled,AccessFailedCount,UserName")] ApplicationUser applicationUser)
{
if (ModelState.IsValid)
{
context.Entry(applicationUser).State = EntityState.Modified;
try
{
context.SaveChanges();
}
catch (System.Data.Entity.Validation.DbEntityValidationException dbEx)
{
Exception raise = dbEx;
foreach (var validationErrors in dbEx.EntityValidationErrors)
{
foreach (var validationError in validationErrors.ValidationErrors)
{ string message = string.Format("{0}:{1}",
validationErrors.Entry.Entity.ToString(),
validationError.ErrorMessage);
// raise a new exception nesting
// the current instance as InnerException
raise = new InvalidOperationException(message, raise);
}
}
throw raise;
}
return RedirectToAction("ListUsers","Account");
}
return View(applicationUser);
}

Related

MVC, Edit View problem with getting existing data in form

I got a problem when I create edit view. I run program, from index view and click on edit on some data.
Issuse is that Im getting empty form(I can save it to database normaly) but I want to see what I entered and than edit some parts of data and save it.
public ActionResult Edit(int Id)
{
IEnumerable<Country> CountryList = db.Countries.ToList();
ViewBag.CountryList = new SelectList(CountryList, "CountryId", "CountryName");
ViewBag.Id = Id;
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(EditStateContactViewModel csvm)
{
if (!ModelState.IsValid)
{
return View(csvm);
}
Contact item = db.Contacts.First(x => x.ContactId == csvm.ContactId);
item.CountryId = csvm.CountryId;
item.StateId = csvm.StateId;
item.ImeOsobe = csvm.ImeOsobe;
item.PrezimeOsobe = csvm.PrezimeOsobe;
item.Komentar = csvm.Komentar;
item.Email = csvm.Email;
item.Aktivan = csvm.Aktivan;
item.kcbr = csvm.kcbr;
item.KucniBroj = csvm.KucniBroj;
item.NazivUlice = csvm.NazivUlice;
item.NazivNaselja = csvm.NazivNaselja;
item.PostanskiBroj = csvm.PostanskiBroj;
item.KontaktBroj = csvm.KontaktBroj;
try
{
db.SaveChanges();
}
catch (System.Data.Entity.Validation.DbEntityValidationException db)
{
Exception raise = db;
foreach (var validationErrors in db.EntityValidationErrors)
{
foreach (var validationError in validationErrors.ValidationErrors)
{
string message = string.Format("{0}:{1}",
validationErrors.Entry.Entity.ToString(),
validationError.ErrorMessage);
raise = new InvalidOperationException(message, raise);
}
}
throw raise;
}
return RedirectToAction("Index");
}
public class EditStateContactViewModel : CountryStateContactViewModel
{
public int Id { get; set; }
}
And View
#model AkvizicijeApp_4_2.Models.EditStateContactViewModel
<div class="form-horizontal">
<h4>CountryStateContactViewModel</h4>
<hr />
<h2>Edit</h2>
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.CountryId, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.CountryId, ViewBag.CountryList as SelectList, "--Select Country--", new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.CountryId, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.StateId, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.StateId, new SelectList(" "), "--Select State--", new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.StateId, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.ContactId, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.ContactId, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.ContactId, "", new { #class = "text-danger" })
</div>
</div>
.....
and scripts from View for Parent-Child dropdown lists
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
<script src="~/Scripts/jquery-3.3.1.min.js"></script>
<script>
$(document).ready(function () {
$("#CountryId").change(function () {
$.get("/Home/GetStateList", { CountryId: $("#CountryId").val() }, function (data) {
$("#StateId").empty();
$.each(data, function (index, row) {
$("#StateId").append("<option value='" + row.StateId + "'>" + row.StateName + "</option>")
});
});
})
});
</script>
You didn't select existing data to edit form.
You need to load your DB data to viewmodel and pass your viewmodel to cshtml by return View(vm):
[HttpGet]
public ActionResult Edit(int Id)
{
IEnumerable<Country> CountryList = db.Countries.ToList();
ViewBag.CountryList = new SelectList(CountryList, "CountryId", "CountryName");
ViewBag.Id = Id;
var item = db.Contacts.First(x => x.ContactId == Id);
var vm = new EditStateContactViewModel();
vm.Id = Id;
vm.NazivNaselja = item.NazivNaselja;
...
return View(vm);
}

Redirect user to original url after login in asp net mvc

i want to redirect original page after login
public ActionResult UnAuthorize(string ReturnUrl)
{
return Redirect("/Account/SignIn?ReturnUrl=" + ReturnUrl);
}
url : http://localhost:18908/Account/SignIn?ReturnUrl=/Customer/Index
public JsonResult SignIn(SignInModel model, string returnUrl)
{
try
{
return Redirect(returnUrl);
}
But returnUrl return value of null or empty
using System;
using System.Web.Mvc;
namespace WebApplication1.Controllers
{
public class SignInModel
{
public string Name { get; set; }
}
public class AccountController : Controller
{
public ActionResult UnAuthorize(string ReturnUrl)
{
return Redirect("/Account/SignIn?ReturnUrl=" + ReturnUrl);
}
[HttpGet]
public ActionResult SignIn(string returnUrl)
{
ViewBag.ReturnUrl = returnUrl;
return View();
}
[HttpPost]
public ActionResult SignIn(SignInModel model, string returnUrl)
{
try
{
return Redirect(returnUrl);
}
catch (Exception ex)
{
throw;
}
}
}
}
SignIn view
#model WebApplication1.Controllers.SignInModel
#{
ViewBag.Title = "View";
}
<h2>View</h2>
#using (Html.BeginForm("SignIn", "Account", new { ReturnUrl = ViewBag.ReturnUrl }))
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>SignInModel</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<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.Name, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Name, "", 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>
Customer Index View
#{
ViewBag.Title = "Customers";
}
<h2>Customer</h2>
Focus on HttpGet SingIn action and SignIn view.
try: http://localhost:18908/Account/UnAuthorize?ReturnUrl=/Customer/Index

Default Value for DropDownList COntrols on ASP.NET MVC [duplicate]

This question already has answers here:
mvc 5 SelectList from table with blank value for DropDownList
(4 answers)
Closed 4 years ago.
i am new to MVC (database first), and i have a question
I have a form, with a DropDownList control. the DropDownList Control has been bound to a column on a database, but i want to have as part of the items, a default value e.g "--select grade--"
how do i go about this?
i have a couple of views and controllers generated from scaffolding.
i will attach my view as well as my controller for the particular object.
DropDownLists #Html.DropDownList("StudentID", null, htmlAttributes: new { #class = "form-control" })
and
#Html.DropDownList("CourseID", null, htmlAttributes: new { #class = "form-control" })
are the concerns
#model ContosoSite.Models.Enrollment
#{
ViewBag.Title = "Create";
}
<h2>Create</h2>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Enrollment</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.Grade, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Grade, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Grade, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.CourseID, "CourseID", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("CourseID", null, htmlAttributes: new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.CourseID, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.StudentID, "StudentID", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("StudentID", null, htmlAttributes: new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.StudentID, "", 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>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using ContosoSite.Models;
namespace ContosoSite.Controllers
{
public class EnrollmentsController : Controller
{
private ContosoUniversityEntities db = new ContosoUniversityEntities();
// GET: Enrollments
public ActionResult Index()
{
var enrollments = db.Enrollments.Include(e => e.Course).Include(e => e.Student);
return View(enrollments.ToList());
}
// GET: Enrollments/Details/5
public ActionResult Details(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Enrollment enrollment = db.Enrollments.Find(id);
if (enrollment == null)
{
return HttpNotFound();
}
return View(enrollment);
}
// GET: Enrollments/Create
public ActionResult Create()
{
ViewBag.CourseID = new SelectList(db.Courses, "CourseID", "Title");
ViewBag.StudentID = new SelectList(db.Students, "StudentID", "LastName");
return View();
}
// POST: Enrollments/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see https://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "EnrollmentID,Grade,CourseID,StudentID")] Enrollment enrollment)
{
if (ModelState.IsValid)
{
db.Enrollments.Add(enrollment);
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.CourseID = new SelectList(db.Courses, "CourseID", "Title", enrollment.CourseID);
ViewBag.StudentID = new SelectList(db.Students, "StudentID", "LastName", enrollment.StudentID);
return View(enrollment);
}
// GET: Enrollments/Edit/5
public ActionResult Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Enrollment enrollment = db.Enrollments.Find(id);
if (enrollment == null)
{
return HttpNotFound();
}
ViewBag.CourseID = new SelectList(db.Courses, "CourseID", "Title", enrollment.CourseID);
ViewBag.StudentID = new SelectList(db.Students, "StudentID", "LastName", enrollment.StudentID);
return View(enrollment);
}
// POST: Enrollments/Edit/5
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see https://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "EnrollmentID,Grade,CourseID,StudentID")] Enrollment enrollment)
{
if (ModelState.IsValid)
{
db.Entry(enrollment).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.CourseID = new SelectList(db.Courses, "CourseID", "Title", enrollment.CourseID);
ViewBag.StudentID = new SelectList(db.Students, "StudentID", "LastName", enrollment.StudentID);
return View(enrollment);
}
// GET: Enrollments/Delete/5
public ActionResult Delete(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Enrollment enrollment = db.Enrollments.Find(id);
if (enrollment == null)
{
return HttpNotFound();
}
return View(enrollment);
}
// POST: Enrollments/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(int id)
{
Enrollment enrollment = db.Enrollments.Find(id);
db.Enrollments.Remove(enrollment);
db.SaveChanges();
return RedirectToAction("Index");
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
}
}
Razor view:
#Html.DropDownList("StudentGender",
new SelectList(Enum.GetValues(typeof(Gender))),
"Select Gender",
new { #class = "form-control" })
Result:
<select class="form-control" id="StudentGender" name="StudentGender">
<option>Select Gender</option>
<option>Male</option>
<option>Female</option>
</select>
Ref. http://www.tutorialsteacher.com/mvc/htmlhelper-dropdownlist-dropdownlistfor
You can use this overload of the DropDownList helper method.
public static DropDownList (thisHtmlHelper htmlHelper,
string name,
IEnumerable<System.Web.Mvc.SelectListItem> selectList,
string optionLabel,
IDictionary<string,object> htmlAttributes);
Here the third parameter optionLabel is used to build the an option item for for the default item. The option will not have a value attribute value.
So in your case, your view code will be
#Html.DropDownList("CourseID", ViewBag.CourseID as SelectList,
"--select grade--", new { #class = "form-control" })
This will render a SELECT element where the first option will be "select grade" and that will be selected (because it is first). If you want some other option item to be selected as default, consider using the DropDownListFor helper method with a view model. Refer this post for sample code on that approach.

Form Submit Not Work in MVC 5 Project

My Submit Form Button Not Working ..
When I press on Login Button Nothing Happens ...
I had set breakpoint in my code and Login Post Action not Called after Submit Button Click .
I can fix my problem with JQuery ajax codes but I don't want use JQuery Ajax for submitting Form ..I want to understand and resolve this MVC problem
thank you ...
User Model :
namespace Models
{
public class User : BaseEntity
{
public User() : base()
{
}
[System.ComponentModel.DataAnnotations.Required]
public string Username { get; set; }
[System.ComponentModel.DataAnnotations.Required]
[System.ComponentModel.DataAnnotations.DataType(System.ComponentModel.DataAnnotations.DataType.Password)]
public string Password { get; set; }
}
}
BaseEntity Class has only Id (System.Guid) Property
Controller :
public class AdminController : Infrastructure.BaseController
{
[System.Web.Mvc.HttpGet]
public System.Web.Mvc.ActionResult Index()
{
return View();
}
[System.Web.Mvc.HttpGet]
public System.Web.Mvc.ActionResult Login()
{
return View();
}
[System.Web.Mvc.HttpGet]
public System.Web.Mvc.ActionResult Edit()
{
return View();
}
[System.Web.Mvc.HttpPost]
[System.Web.Mvc.ValidateAntiForgeryToken]
public System.Web.Mvc.ActionResult Login([System.Web.Mvc.Bind(Include = "Id,Username,Password")] Models.User user)
{
string password = AAk.Security.Hashing.GetMD5(user.Password);
Models.User oUser = MyDatabaseContext.Users
.Where(current => current.Username.Contains(user.Username))
.Where(current => current.Password == password)
.FirstOrDefault();
if(oUser != null)
{
System.Web.Security.FormsAuthentication.SetAuthCookie(user.Username, false);
Session["AdminUserId"] = user.Id;
return (RedirectToAction("Edit", "Admin"));
}
else
{
//ModelState.AddModelError(string.Empty, "Login Failed!");
PageMessages.Add(new Infrastructure.PageMessage(Infrastructure.PageMessage.Types.Error, "Login Failed!"));
}
return (View(model: user));
}
}
Login.cshtml
#model Models.User
#{
ViewBag.Title = "Login";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Login</h2>
#using (Html.BeginForm("Login", "Admin", FormMethod.Post))
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
#Html.Partial(partialViewName: "~/Views/Shared/_PageMessages.cshtml")
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
#Html.HiddenFor(model => model.Id)
<div class="form-group">
#Html.LabelFor(model => model.Username, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Username, new { htmlAttributes = new { #class = "form-control", #id = "username" } })
#Html.ValidationMessageFor(model => model.Username, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Password, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Password, new { htmlAttributes = new { #class = "form-control", #id = "password" } })
#Html.ValidationMessageFor(model => model.Password, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Login" class="btn btn-default" id="login-button" />
</div>
</div>
</div>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>

Passing data from view to method Create in controller [duplicate]

This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 5 years ago.
I have the following problem with passing data to metod create in controller.
First I display view for method create (GET)
public ActionResult Create(string id)
{
RolesUser RolesUser = new RolesUser(id,repository.GetUserById(id).Roles, repository.GetRoles().ToList());
return View(RolesUser);
}
I use the following ViewModel
public class RolesUser
{
public RolesUser()
{
}
public RolesUser(string id,ICollection<IdentityUserRole> userRoles,List<IdentityRole> Roles)
{
userId = id;
this.Roles = GetNewRolesForUser(userRoles.ToList(), Roles.ToDictionary(x => x.Id, x => x.Name)).ConvertAll(
role =>
{
return new SelectListItem()
{
Text = role.ToString(),
Value = role.ToString(),
Selected = false
};
});
}
public IEnumerable<SelectListItem> Roles { get; set; }
public string userId { get; set; }
private List<string> GetNewRolesForUser(List<IdentityUserRole> UserRoles,Dictionary<string,string> Roles)
{
List<string> AvaiableRoles = new List<string>();
List<string> IdUserRoles = new List<string>();
UserRoles.ForEach(item => IdUserRoles.Add(item.RoleId));
foreach(KeyValuePair<string,string> Role in Roles)
{
if (!IdUserRoles.Contains(Role.Key))
{
AvaiableRoles.Add(Role.Value);
}
}
return AvaiableRoles;
}
}
It displays me essential information on my view in Create.cshtml, when I execute Submit it shows me following error
Object reference not set to an instance of an object.
The metod create (POST) looks like this
[HttpPost]
[ValidateAntiForgeryToken]
[Authorize(Roles ="Admin")]
public ActionResult Create([Bind(Include ="userId")] RolesUser user)
{
if (ModelState.IsValid)
{
try
{
repository.AssignToRole(user.userId, "Klient");
repository.SaveChanges();
}
catch
{
ViewBag.exception = true;
return View();
}
}
ViewBag.exception = false;
return RedirectToAction("Index");
}
Code for Create.cshtml
#model Repository.ViewModels.RolesUser
#{
ViewBag.Title = "Create";
}
<h2>Dodaj poziom dostępu</h2>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>#Model.userId</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.userId, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DisplayFor(model => model.userId, new { htmlAttributes = new { #class = "form-control" } })
</div>
</div>
<div class="form-group">
#Html.Label("Poziomy dostępu", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(m => m.userId, Model.Roles)
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Dodaj" class="btn btn-default" />
</div>
</div>
</div>
}
It looks like viewmodel is not passing to method, so I have null exception. But I don't understand why, if GET metod render properly view.
The NullReferenceException is likely hit inside the repository.AssignToRole() method because user.userId is null. You should add a hidden input for the userId somewhere inside the form so the userId value is posted to the parameter object on the Create action. If you add it after the #Html.AntiForgeryToken() the start of the form would look like
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
#Html.HiddenFor(model => model.userId)
...

Resources