Asp.net core Identity multiple roles to user - asp.net-core

I am working on asp.net core 3.1 project. There are several types of users in project. For example :
Some of users type
Admin
writer
Manager
Accountants
Operator
and ...
Users type are different and may increase or decrease. We may have 20 writers or 100 operators users in this project that all writers or all operators have same roles.
Now i can set roles to user manually. But i want to set a bunch of roles to users.
For example if user type was operator all roles depends on operator set to user.

I create a simple demo which you could choose UserType when you register a user. And assign all related roles of the UserType to user.
1.Models:
public class ApplicationUser : IdentityUser
{
[ForeignKey("UserType")]
public int UserTypeId {get;set;}
public UserType UserType { get; set; }
}
public class UserType
{
[Key]
public int Id { get; set; }
public string Name { get; set; }
public List<ApplicationUser> Users { get; set; }
public List<ApplicationRole> Roles { get; set; }
}
public class ApplicationRole : IdentityRole
{
[ForeignKey("UserType")]
public int? UserTypeId {get;set;}
public UserType UserType { get; set; }
}
2.DbContext
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options)
{
}
public DbSet<UserType> UserTypes { get; set; }
public DbSet<ApplicationRole> AppRoles { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<ApplicationUser>()
.HasOne(c => c.UserType)
.WithMany(u=>u.Users)
.OnDelete(DeleteBehavior.Restrict);
}
}
3.Register.cshtml.cs
public class InputModel
{
[Required]
[EmailAddress]
[Display(Name = "Email")]
public string Email { get; set; }
[Required]
[StringLength(100, ErrorMessage = "The {0} must be at least {2} and at max {1} 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 int UserTypeId { get; set; }
}
public async Task OnGetAsync(string returnUrl = null)
{
ViewData["UserType"] = new SelectList(_context.UserTypes, "Id", "Name");
ReturnUrl = returnUrl;
ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList();
}
public async Task<IActionResult> OnPostAsync(string returnUrl = null)
{
returnUrl = returnUrl ?? Url.Content("~/");
ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList();
if (ModelState.IsValid)
{
var user = new ApplicationUser { UserName = Input.Email, Email = Input.Email, UserTypeId = Input.UserTypeId };
var result = await _userManager.CreateAsync(user, Input.Password);
if (result.Succeeded)
{
//add bunch of roles to user
var roles = _context.AppRoles.Where(r => r.UserTypeId == user.UserTypeId).Select(r => r.Name).ToList();
foreach(var role in roles)
{
await _userManager.AddToRoleAsync(user, role);
}
//...
}
foreach (var error in result.Errors)
{
ModelState.AddModelError(string.Empty, error.Description);
}
}
// If we got this far, something failed, redisplay form
return Page();
}
4.Register.cshtml
<form asp-route-returnUrl="#Model.ReturnUrl" method="post">
<h4>Create a new account.</h4>
<hr />
<div asp-validation-summary="All" class="text-danger"></div>
<div class="form-group">
<label asp-for="Input.Email"></label>
<input asp-for="Input.Email" class="form-control" />
<span asp-validation-for="Input.Email" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Input.Password"></label>
<input asp-for="Input.Password" class="form-control" />
<span asp-validation-for="Input.Password" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Input.ConfirmPassword"></label>
<input asp-for="Input.ConfirmPassword" class="form-control" />
<span asp-validation-for="Input.ConfirmPassword" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Input.UserTypeId"></label>
<select asp-for="Input.UserTypeId" asp-items="#ViewBag.UserType" class="form-control"></select>
</div>
<button type="submit" class="btn btn-primary">Register</button>
</form>
4.Startup.cs
services.AddDefaultIdentity<ApplicationUser>()
.AddRoles<ApplicationRole>()
.AddEntityFrameworkStores<ApplicationDbContext>();

Related

Cannot update user Identity Role from list in razor page

I have a razor page which shows checkbox of Roles. The Roles owned by the selected user will be checked on page load. What I'm trying to do is, I want to be able to edit the roles for the selected user. But when I click update, it doesn't update.
Here is the razor page:
<EditForm Model="#RoleDto" OnValidSubmit="#EditRole">
<DataAnnotationsValidator />
<ValidationSummary />
<div class="card">
<div class="card-header">
<h2>Manage User Roles</h2>
Add/Remove Roles for User / #UserFullname
</div>
<div class="card-body">
#for (int i = 0; i < numOfRoles; i++)
{
<div class="form-check m-1">
<input type="hidden" value="#RoleListModel[i].Id" />
<input type="hidden" value="#RoleListModel[i].Name" />
<input type="checkbox" checked="#RoleListModel[i].Selected" /> #RoleListModel[i].Name
</div>
}
</div>
</div>
<button type="submit" class="btn btn-success btn-block">
Confirm
</button>
#code {
ApplicationRoleDto RoleDto = new ApplicationRoleDto();
private List<ApplicationRoleDto> RoleListModel;
[Parameter] public string Id { get; set; }
[Parameter] public ApplicationUserDto UserDto { get; set; }
[Parameter] public string UserFullname { get; set; }
[Parameter] public int numOfRoles { get; set; }
protected async override Task OnParametersSetAsync()
{
UserDto = await _client.GetFromJsonAsync<ApplicationUserDto>($"api/userroles/{Id}");
UserFullname = UserDto.FullName;
RoleListModel = await _client.GetFromJsonAsync<List<ApplicationRoleDto>>($"api/rolemanager/{Id}");
numOfRoles = RoleListModel.Count();
}
async Task EditRole()
{
await _client.PostAsJsonAsync($"api/rolemanager/{Id}", RoleListModel);
_navManager.NavigateTo($"/userroles/");
}
}
and here is the controller:
[HttpPost]
public async Task<IActionResult> Manage(List<ApplicationRoleDto> model, string Id)
{
var user = await _userManager.FindByIdAsync(Id);
if (user == null)
{
NotFound();
}
var roles = await _userManager.GetRolesAsync(user);
var result = await _userManager.RemoveFromRolesAsync(user, roles);
if (!result.Succeeded)
{
Console.WriteLine("Cannot remove user existing roles");
return NotFound();
}
result = await _userManager.AddToRolesAsync(user, model.Where(x => x.Selected).Select(y => y.Name));
if (!result.Succeeded)
{
Console.WriteLine("Cannot add selected roles to user");
return NotFound();
}
return NoContent();
}
Did I miss anything here?

How to represent a Question/Answer page inside my asp.net MVC core web application

I have the following 3 models, which represents a submission of questions/answers:-
public partial class Submission
{
public Submission()
{
SubmissionQuestionSubmission = new HashSet<SubmissionQuestionSubmission>();
}
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public bool Independent { get; set; }
public string Comment { get; set; }
public virtual ICollection<SubmissionQuestionSubmission> SubmissionQuestionSubmission { get; set; }
}
public partial class SubmissionQuestion
{
public SubmissionQuestion()
{
SubmissionQuestionSubmission = new HashSet<SubmissionQuestionSubmission>();
}
public int Id { get; set; }
public string Question { get; set; }
public virtual ICollection<SubmissionQuestionSubmission> SubmissionQuestionSubmission { get; set; }
}
public partial class SubmissionQuestionSubmission
{
public int SubmissionQuestionId { get; set; }
public int SubmissionId { get; set; }
public string Answer { get; set; }
public virtual Submission Submission { get; set; }
public virtual SubmissionQuestion SubmissionQuestion { get; set; }
}
now i want to build a view which will show the submission firstname,lastname & comments + all the questions and for each question to show the answer fields as a free text for the user to enter it. to be honest i am not sure how i need to build the view and receive it inside the action method? any help?
It seems you want to display the data of specified submission's firstname,lastname,comments,the related questions.And with each question,you could enter an answer.Then pass the filled data to the action.
Here is a simple demo like below:
Model:
public class ViewModel
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string Comment { get; set; }
public List<string> Question { get; set; }
public List<string> Answer { get; set; }
}
public partial class Submission
{
public Submission()
{
SubmissionQuestionSubmission = new HashSet<SubmissionQuestionSubmission>();
}
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public bool Independent { get; set; }
public string Comment { get; set; }
public virtual ICollection<SubmissionQuestionSubmission> SubmissionQuestionSubmission { get; set; }
}
public partial class SubmissionQuestion
{
public SubmissionQuestion()
{
SubmissionQuestionSubmission = new HashSet<SubmissionQuestionSubmission>();
}
public int Id { get; set; }
public string Question { get; set; }
public virtual ICollection<SubmissionQuestionSubmission> SubmissionQuestionSubmission { get; set; }
}
public partial class SubmissionQuestionSubmission
{
public int SubmissionQuestionId { get; set; }
public int SubmissionId { get; set; }
public string Answer { get; set; }
public virtual Submission Submission { get; set; }
public virtual SubmissionQuestion SubmissionQuestion { get; set; }
}
View(If you want to edit the firstname,lastname..you could remove the readonly):
#model ViewModel
<div class="row">
<div class="col-md-4">
<form asp-action="Create">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="FirstName" class="control-label"></label>
<input asp-for="FirstName" class="form-control" readonly />
<span asp-validation-for="FirstName" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="LastName" class="control-label"></label>
<input asp-for="LastName" class="form-control" readonly />
<span asp-validation-for="LastName" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Comment" class="control-label"></label>
<input asp-for="Comment" class="form-control" readonly />
<span asp-validation-for="Comment" class="text-danger"></span>
</div>
#for (var i = 0; i < Model.Question.Count(); i++)
{
<label>#Model.Question[i]</label><br />
<input asp-for="#Model.Question[i]" hidden />
<input asp-for="#Model.Answer[i]" />
<br />
}
<div class="form-group">
<input type="submit" value="Create" class="btn btn-primary" />
</div>
</form>
</div>
</div>
Controller:
public async Task<IActionResult> Create()
{
//specified one submissions' data and the related questions
var model = await _context.Submission.Include(s => s.SubmissionQuestionSubmission)
.ThenInclude(s => s.SubmissionQuestion).Select(s => new ViewModel()
{
FirstName = s.FirstName,
LastName = s.LastName,
Comment = s.Comment,
Question = s.SubmissionQuestionSubmission.Where(s => s.SubmissionId == 1).Select(s => s.SubmissionQuestion.Question).ToList(),
}).FirstOrDefaultAsync();
return View(model);
}
[HttpPost]
public async Task<IActionResult> Create(ViewModel submission)
{
//do your stuff...
return View();
}
Result:

How to post HttpPostedFileBase with Model data from MVC

How to upload file with HttpPostedFileBase with 3 other Model data
and save it to database.When i try to save data employee model value
become null and give object reference error.I have a Create view link
for New employee on Get Page. I am getting object refrence error when
try to save.
EmployeeModelClass.cs
public class EmployeeViewModel
{
public Employee Employee { get; set; }
public HttpPostedFileBase File { get; set; }
public List<Employee> EmployeeList { get; set; }
public IEnumerable<Region> Regions { get;set; }
public IEnumerable<City> Cities { get; set; }
}
EmployeClass
public class Employee
{
[Key]
public int EmployeeId { get; set; }
public string Name { get; set; }
[DataType(DataType.DateTime)]
public DateTime? BirthDate { get; set; }
[Display(Name = "Region")]
public int RegionId { get; set; }
public City City { get; set; }
[Display(Name = "City")]
public int CityId { get; set; }
[DataType(DataType.Password)]
public string Password { get; set; }
[DataType(DataType.Password)]
public string Confirm Password { get; set; }
public int ImageSize { get; set; }
public string FileName { get; set; }
public byte[] ImageData { get; set; }
}
Get Request for Create.And here i am redirect from Get.chtml view.
[HttpGet]
public ActionResult Create()
{
var viewmodel = new EmployeeViewModel
{
Regions = _context.Regions.ToList(),
Cities = _context.Cities.ToList(),
};
return View("Create", viewmodel);
}
Post Request for Create .Here my employee model value becoming null and on submit give object refrence null error.
[HttpPost]
public ActionResult Create(HttpPostedFileBase file,Employee emp)
{
}
Create.chtml
#model EmployeeManagement.ViewModel.EmployeeViewModel
#{
ViewBag.Title = "Create";
}
<h2>Create</h2>
#using (#Html.BeginForm("Create", "Employee", FormMethod.Post, new {
enctype = "multipart/form-data" }))
{
<div class = "form-group">
#Html.LabelFor(m => m.Employee.Name)
#Html.TextBoxFor(m => m.Employee.Name, new { #class = "form-control"
})
</div>
<div class = "form-group">
#Html.LabelFor(m => m.Employee.BirthDate)
#Html.TextBoxFor(m => m.Employee.BirthDate, new { #class = "form-
control" })
</div>
<div class="form-group">
#Html.LabelFor(m => m.Employee.RegionId)
#Html.DropDownListFor(m => m.Employee.RegionId, new
SelectList(Model.Regions, "RegionId", "RegionName"), "Please Select
Region", new { #onchange = "BindCity()", #class = "form-control" })
#Html.ValidationMessageFor(m => m.Employee.RegionId)
</div>
<div class="form-group">
#Html.LabelFor(m => m.Employee.CityId)
#Html.DropDownListFor(m => m.Employee.CityId, new
SelectList(Model.Cities, "CityId", "CityName"), "Please Select
City", new { #class = "form-control" })
#Html.ValidationMessageFor(m => m.Employee.CityId)
</div>
<div class="form-group">
#Html.LabelFor(m => m.Employee.Password)
#Html.PasswordFor(m => m.Employee.Password, new { #class = "form-
control" })
</div>
<div class="form-group">
#Html.LabelFor(m => m.Employee.ConfirmPassword)
#Html.PasswordFor(m => m.Employee.ConfirmPassword, new { #class =
"form-control" })
</div>
<div>
#Html.TextBoxFor(m=>m.File, new { type = "file",name="File" })
#Html.ValidationMessageFor(m=>m.File.FileName)
</div>
<p><button type="submit" class="btn btn-primary">Save</button></p>
}
Please someone help how to upload image with model data at
post.
The problem in your Post Create method you are expecting Employee object but you are binding EmployeeViewModel with view so use below line it's resolve your issue.
public ActionResult Create(HttpPostedFileBase file,EmployeeViewModel emp)

How to combine two entities in one view?

I need to display the records of the student which is the Student Attempts.
It should look something like this.
https://www.dropbox.com/s/pmazbug2j8xwehe/Example.PNG (Click for image)
But this is the Question page which shows all the correct answers. For the Student Attempts page should be exactly like that only the answers/options are replaced by the answers they attempted so when it is correct, the word will be in green and the wrong ones will be in red.
For this to happen I have to retrieve 2 data from two different entities.
Below is the IQuestion table and QuestionContent is the attribute that holds the model answers and the StudentAttempts table and Answer is the attribute that holds the answers attempted by the students.
https://www.dropbox.com/s/f92f8zvk9qn1n8p/DB%20Tables.PNG (Click for image)
How do I combine those two attributes to display in a view?
StudentAttemptsController.cs
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using iStellarMobile.Models;
namespace iStellarMobile.Controllers
{
public class StudentAttemptsController : Controller
{
private istellarEntities db = new istellarEntities();
//
// GET: /StudentAttempts/
public ActionResult Index(int id)
{
var studentattempts = db.StudentAttempts.Include(s => s.activity).Include(s => s.task).Include(s => s.UserInfo).Where(s => s.StudentID == id);
return View(studentattempts.ToList());
}
//
// GET: /StudentAttempts/Details/5
public ActionResult Details(int id = 0)
{
StudentAttempt studentattempt = db.StudentAttempts.Find(id);
if (studentattempt == null)
{
return HttpNotFound();
}
return View(studentattempt);
}
//
// GET: /StudentAttempts/Create
public ActionResult Create()
{
ViewBag.ActivityID = new SelectList(db.activities, "ActivityID", "ActivityName");
ViewBag.TaskID = new SelectList(db.tasks, "TaskID", "TaskName");
ViewBag.StudentID = new SelectList(db.UserInfoes, "ID", "UserName");
return View();
}
//
// POST: /StudentAttempts/Create
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(StudentAttempt studentattempt)
{
if (ModelState.IsValid)
{
db.StudentAttempts.Add(studentattempt);
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.ActivityID = new SelectList(db.activities, "ActivityID", "ActivityName", studentattempt.ActivityID);
ViewBag.TaskID = new SelectList(db.tasks, "TaskID", "TaskName", studentattempt.TaskID);
ViewBag.StudentID = new SelectList(db.UserInfoes, "ID", "UserName", studentattempt.StudentID);
return View(studentattempt);
}
//
// GET: /StudentAttempts/Edit/5
public ActionResult Edit(int id = 0)
{
StudentAttempt studentattempt = db.StudentAttempts.Find(id);
if (studentattempt == null)
{
return HttpNotFound();
}
ViewBag.ActivityID = new SelectList(db.activities, "ActivityID", "ActivityName", studentattempt.ActivityID);
ViewBag.TaskID = new SelectList(db.tasks, "TaskID", "TaskName", studentattempt.TaskID);
ViewBag.StudentID = new SelectList(db.UserInfoes, "ID", "UserName", studentattempt.StudentID);
return View(studentattempt);
}
//
// POST: /StudentAttempts/Edit/5
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(StudentAttempt studentattempt)
{
if (ModelState.IsValid)
{
db.Entry(studentattempt).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.ActivityID = new SelectList(db.activities, "ActivityID", "ActivityName", studentattempt.ActivityID);
ViewBag.TaskID = new SelectList(db.tasks, "TaskID", "TaskName", studentattempt.TaskID);
ViewBag.StudentID = new SelectList(db.UserInfoes, "ID", "UserName", studentattempt.StudentID);
return View(studentattempt);
}
//
// GET: /StudentAttempts/Delete/5
public ActionResult Delete(int id = 0)
{
StudentAttempt studentattempt = db.StudentAttempts.Find(id);
if (studentattempt == null)
{
return HttpNotFound();
}
return View(studentattempt);
}
//
// POST: /StudentAttempts/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(int id)
{
StudentAttempt studentattempt = db.StudentAttempts.Find(id);
db.StudentAttempts.Remove(studentattempt);
db.SaveChanges();
return RedirectToAction("Index");
}
protected override void Dispose(bool disposing)
{
db.Dispose();
base.Dispose(disposing);
}
}
}
IQuestion.cs (Models)
namespace iStellarMobile.Models
{
using System;
using System.Collections.Generic;
public partial class IQuestion
{
public int ID { get; set; }
public Nullable<int> ActivityID { get; set; }
public Nullable<int> TaskID { get; set; }
public Nullable<int> CategoriesID { get; set; }
public Nullable<bool> Sentence { get; set; }
public string QuestionContent { get; set; }
public string ImageURL { get; set; }
public string CreatedBy { get; set; }
public Nullable<System.DateTime> CreatedOn { get; set; }
public string UpdateBy { get; set; }
public Nullable<System.DateTime> UpdateOn { get; set; }
public Nullable<int> SchoolID { get; set; }
public Nullable<int> DLevel { get; set; }
public Nullable<int> TagID { get; set; }
public virtual ActivityTask ActivityTask { get; set; }
public virtual Category Category { get; set; }
public virtual School School { get; set; }
public virtual Tag Tag { get; set; }
}
}
StudentAttempts.cs (Models)
namespace iStellarMobile.Models
{
using System;
using System.Collections.Generic;
public partial class StudentAttempt
{
public int ID { get; set; }
public Nullable<int> ActivityID { get; set; }
public Nullable<int> TaskID { get; set; }
public Nullable<int> StudentID { get; set; }
public string Answer { get; set; }
public string Score { get; set; }
public Nullable<int> Attempts { get; set; }
public string AttemptDate { get; set; }
public string CorrectAnswer { get; set; }
public virtual activity activity { get; set; }
public virtual task task { get; set; }
public virtual UserInfo UserInfo { get; set; }
}
}
Details.cshtml (StudentAttempts view)
<fieldset>
<legend>Classes</legend>
<div class="editor-label">
<h2> #Html.LabelFor(model => model.activity.ActivityName) </h2>
</div>
<div class="display-field">
#Html.DisplayFor(model => model.activity.ActivityName)
</div>
<br />
<div class="editor-label">
<h2> #Html.LabelFor(model => model.task.TaskName) </h2>
</div>
<div class="display-field">
#Html.DisplayFor(model => model.task.TaskName)
</div>
<br />
<div class="editor-label">
<h2> #Html.LabelFor(model => model.UserInfo.UserName) </h2>
</div>
<div class="display-field">
#Html.DisplayFor(model => model.UserInfo.UserName)
</div>
<br />
<div class="editor-label">
<h2> #Html.LabelFor(model => model.Answer) </h2>
</div>
<div class="display-field">
#Html.DisplayFor(model => model.Answer)
</div>
<br />
<div class="editor-label">
<h2> #Html.LabelFor(model => model.Score) </h2>
</div>
<div class="display-field">
#Html.DisplayFor(model => model.Score)
</div>
<br />
<div class="editor-label">
<h2> #Html.LabelFor(model => model.Attempts) </h2>
</div>
<div class="display-field">
#Html.DisplayFor(model => model.Attempts)
</div>
<br />
<div class="editor-label">
<h2> #Html.LabelFor(model => model.AttemptDate) </h2>
</div>
<div class="display-field">
#Html.DisplayFor(model => model.AttemptDate)
</div>
<br />
<div class="editor-label">
<h2> #Html.LabelFor(model => model.CorrectAnswer) </h2>
</div>
<div class="display-field">
#Html.DisplayFor(model => model.CorrectAnswer)
</div>
</fieldset>
<br />
<p>
#Html.ActionLink("Edit", "/Edit/2",null, new { id=Model.ID, #class="classname" })
<span> </span>
#Html.ActionLink("Back", "/Index", null, new { #class="classname" })
</p>
You could just make a new class type (something like "StudentAttempsVM") that has a property for each of the classes you need (Details and Attempts). Then consolidate your Controller methods to build this object and pass it to your view.

System.NullReferenceException: Object reference not set to an instance of an object. bootstrap dropdownlist

Model
public class Employee
{
public int EmployeeID { get; set; }
public string Title { get; set; }
[Required(ErrorMessage = "Please enter first name.")]
[StringLength(500)]
public string FirstName { get; set; }
public string MI { get; set; }
[Required(ErrorMessage = "Please enter last name.")]
[StringLength(500)]
public string LastName { get; set; }
public string Gender { get; set; }
[Required(ErrorMessage = "Please select date of birth.")]
public Nullable<System.DateTime> DateOfBirth { get; set; }
[Required(ErrorMessage = "Please enter email.")]
[StringLength(500)]
[EmailAddress]
public string Email { get; set; }
[Required(ErrorMessage = "Please enter street.")]
[StringLength(500)]
public string Street { get; set; }
[Required(ErrorMessage = "Please enter state.")]
[StringLength(50)]
public string State { get; set; }
[Required(ErrorMessage = "Please enter city.")]
[StringLength(50)]
public string City { get; set; }
[Required(ErrorMessage = "Please enter country.")]
[StringLength(50)]
public string Country { get; set; }
[Required(ErrorMessage = "Please enter post code.")]
[StringLength(6)]
public string PostCode { get; set; }
[Required(ErrorMessage = "Please enter home phone.")]
public string HomePhone { get; set; }
[Required(ErrorMessage = "Please enter mobile phone.")]
public string MobilePhone { get; set; }
}
Controller Method
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(Employee employee)
{
if (ModelState.IsValid)
{
db.Employees.Add(employee);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(employee);
}
View
#model EmployeeManagementSystem.Models.Employee
#{
ViewBag.Title = "Create";
}
<h2>Create</h2>
<div class="row-fluid">
<div class="span12">
#using (Html.Bootstrap().Begin(new Form().Id("CreateEmployee").Type(FormType.Inline)))
{
#Html.AntiForgeryToken()
<div class="span12">
<fieldset>
<div class="span4">
<legend>Employee Info</legend>
#Html.Bootstrap().ControlGroup().TextBoxFor(x => x.FirstName).Size(InputSize.BlockLevel).ShowValidationMessage(true, HelpTextStyle.Block)
#Html.Bootstrap().ControlGroup().TextBoxFor(x => x.LastName).Size(InputSize.BlockLevel).ShowValidationMessage(true, HelpTextStyle.Block)
#Html.Bootstrap().ControlGroup().DropDownListFor(m => m.Gender, ViewBag.GenderList as SelectList).Size(InputSize.BlockLevel).ShowValidationMessage(true, HelpTextStyle.Block)
#Html.Bootstrap().ControlGroup().Class("input-append date").TextBoxFor(x => x.DateOfBirth).Size(InputSize.BlockLevel).AppendIcon(Icons.calendar).ShowValidationMessage(true, HelpTextStyle.Block)
#Html.Bootstrap().ControlGroup().TextBoxFor(x => x.Email).Size(InputSize.BlockLevel).ShowValidationMessage(true, HelpTextStyle.Block)
</div>
<div class="span8 ">
<legend>Contact Details</legend>
#Html.Bootstrap().ControlGroup().TextBoxFor(x => x.Street).Size(InputSize.BlockLevel).ShowValidationMessage(true, HelpTextStyle.Block)
<div class="span6" style="margin-left:0px">
#Html.Bootstrap().ControlGroup().TextBoxFor(x => x.City).Size(InputSize.BlockLevel).ShowValidationMessage(true, HelpTextStyle.Block)
#Html.Bootstrap().ControlGroup().TextBoxFor(x => x.State).Size(InputSize.BlockLevel).ShowValidationMessage(true, HelpTextStyle.Block)
#Html.Bootstrap().ControlGroup().TextBoxFor(x => x.HomePhone).Size(InputSize.BlockLevel).ShowValidationMessage(true, HelpTextStyle.Block).HtmlAttributes(new Dictionary<string, Object> { { "data-mask", "(99999)(999999)" } })
</div>
<div class="span6">
#Html.Bootstrap().ControlGroup().TextBoxFor(x => x.PostCode).Size(InputSize.BlockLevel).ShowValidationMessage(true, HelpTextStyle.Block)
#Html.Bootstrap().ControlGroup().TextBoxFor(x => x.Country).Size(InputSize.BlockLevel).ShowValidationMessage(true, HelpTextStyle.Block)
#Html.Bootstrap().ControlGroup().TextBoxFor(x => x.MobilePhone).Size(InputSize.BlockLevel).ShowValidationMessage(true, HelpTextStyle.Block).HtmlAttributes(new Dictionary<string, Object> { { "data-mask", "+99 (9999)(999999)" } })
</div>
</div>
</fieldset>
#Html.Bootstrap().SubmitButton().Style(ButtonStyle.Primary)
#Html.Bootstrap().ActionLinkButton("Cancel", "Index").Style(ButtonStyle.Default)
</div>
}
</div>
</div>
#section Scripts {
<script type="text/javascript">
$(document).ready(function () {
//$('[rel=tooltip]').tooltip();
$('#CreateEmployee .input-append.date').datepicker({
startView: 2,
autoclose: true
});
});
</script>
#Scripts.Render("~/bundles/jqueryval")
#Scripts.Render("~/bundles/BootstrapFormHelpersJS")
#Styles.Render("~/Content/BootstrapFormHelpersCSS")
}
Hi this is get method of my controller.
[HttpGet]
public ActionResult Create()
{
List<string> genders = new List<string>();
genders.Add("--Select--");
genders.Add("Male");
genders.Add("Female");
genders.Add("Not Defind");
ViewBag.GenderList = new SelectList(genders, "--Select--");
return View();
}