How to make use of Viewbag in my View - asp.net-mvc-3

I dont understand, I have my in my Controller:
[HttpGet]
public ActionResult Detail(int userId)
{
var user = ZincService.GetUserForId(userId);
if (user != null)
{
ViewBag.user = userId;
ViewBag.email = user.Email;
ViewBag.title = user.JobTitle;
ViewBag.node = user.Node;
}
return View(user);
}
then my view, Detail.aspx
<div id="user-details-view">
<div>
Title:
</div>
<div>
<%: Model.JobTitle %>
<%: Model.News %>
<%: Model.Node %>
</div>
<div>
<%: Html.ActionLink("Change Email Address", "ChangeEmailAddress", new { #id = Model.UserId })%>
</div>
</div>
when I run my app i get an error:
The resource cannot be found.
Description: HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable. Please review the following URL and make sure that it is spelled correctly.
Requested URL: /Areas/Admin/Views/User/Detail.aspx
I dont understand? Is it because of syntax errors?

Previous posts are correct as in logic but you assigned the viewbag names in your controller differently. It should be:
<div id="user-details-view">
<div>
Title:
</div>
<div>
<%: ViewBag.email %>
<%: ViewBag.title %>
<%: ViewBag.node %>
</div>
<div>
<%: Html.ActionLink("Change Email Address", "ChangeEmailAddress", new { #id = ViewBag.user })%>
</div>
</div>
Hope it helps..

It must be like this
<%: ViewBag.JobTitle %>
<%: ViewBag.News %>
<%: ViewBag.Node %>

Replace the Model. with ViewBag.
<%: ViewBag.title %>
<%: ViewBag.email %>
<%: ViewBag.node %>
and also change this
<%: Html.ActionLink("Change Email Address", "ChangeEmailAddress", new { id = ViewBag.user })%>

You must use that sintax:
<%: ViewBag.email %>
<%: ViewBag.title %>
<%: ViewBag.node %>
But would be better if you use Model:
public class UserInfo
{
public int UserId { get; set; }
public string Email { get; set; }
public string Title { get; set; }
public NodeType Node { get; set; }
}
[HttpGet]
public ActionResult Detail( int userId )
{
var data = ZincService.GetUserForId( userId );
var user = new UserInfo();
if ( data != null )
{
user.UserId = userId;
user.Email = data.Email;
user.Title = data.JobTitle;
user.Node = data.Node;
}
return View( user );
}
In view (MVC3) with razor sintax:
#model UserInfo
<div id="user-details-view">
<div>
Title:
</div>
<div>
#Model.Title
#Model.Node
</div>
<div>
#Html.ActionLink("Change Email Address", "ChangeEmailAddress", new { #id = Model.UserId })
</div>
</div>

Related

Return Succes Message After Delete/Update/create

This is my GesAgence Page action :
public ActionResult GesAgence()
{
var test = new Models.J2VEntities();
return View(test.agence);
}
This is my Action for Deleting :
public ActionResult DeleteAg(string id)
{
Models.J2VEntities entity = new Models.J2VEntities();
Models.agence model = (from p in entity.agence
where p.Idag == id
select p).SingleOrDefault();
//Sauvgarde ds la BD
entity.agence.DeleteObject(model);
entity.SaveChanges();
return View("gesAgence");
}
So i'm wondring how to return Succes message after deleting(i tried with TempData but didn't succed because my gesAgence must return model not TempData).
You can use Ajax to call your controller from your viewpage and pop up the message whatever your controller returned, try something like this.
Script on your view page.
function onDeleteAg (id) {
var answer = confirm("Are you sure you want to delete AG ?")
if (answer) {
$.ajax(
{
type: "Get",
url: '<%= Url.Action("DeleteAg","YourControllerName") %>',
data: { agId: id },
success: function (data) {
//HERE--data is the message you that your controller DeleteAg method will return after it's called. you need to do something here to display this message(data) anywhere you want to . something like below.
alert(data);
},
error: (function () { alert("Error! Ag was not deleted." ); })
});
}
};
Method on your controller.
public string DeleteAg(string agId)
{
try{
Models.J2VEntities entity = new Models.J2VEntities();
Models.agence model = (from p in entity.agence
where p.Idag == id
select p).SingleOrDefault();
//Sauvgarde ds la BD
entity.agence.DeleteObject(model);
entity.SaveChanges();
}
catch(Exception ex)
{
return "AG has not been deleted successfully;
}
return "AG has been deleted successfully;
}
you can call this method via ajax and return JsonResult instead of ActionResult, by looking result you can show message to user.
public JsonResult DeleteAg(string id)
{
Models.J2VEntities entity = new Models.J2VEntities();
Models.agence model = (from p in entity.agence
where p.Idag == id
select p).SingleOrDefault();
//Sauvgarde ds la BD
entity.agence.DeleteObject(model);
entity.SaveChanges();
var json = new
{
success = true
};
return Json(json);
}
You can set Success to ViewBag
public ActionResult DeleteAg(string id)
{
Models.J2VEntities entity = new Models.J2VEntities();
Models.agence model = (from p in entity.agence
where p.Idag == id
select p).SingleOrDefault();
//Sauvgarde ds la BD
entity.agence.DeleteObject(model);
entity.SaveChanges();
ViewData["Success"] = true;
return View("gesAgence");
}
in view
#if(ViewData["Success"] != null && (bool)ViewData["Success"]){
<script>alert("Sucess!");</script>
}
This is my view :
<% if(ViewData != null && ViewData["Success"] != null && (bool)ViewData["Success"]){ %>
<script type="text/javascript"> alert("Sucess!");</script>
<% } %>
<div class="clear">
</div>
<div id="main">
<h1> Demande preinscrit</h1>
<ul class="listing">
<% foreach (var item in Model) { %>
<li>
<div class="listinfo">
<h3>
<%: Html.DisplayFor(modelItem => item.Nomag) %>
</h3>
<p>
<%: Html.DisplayFor(modelItem => item.Idag) %>
</p>
<span class="price"> <%: Html.DisplayFor(modelItem => item.Adrag) %> <%: Html.DisplayFor(modelItem => item.Vilag) %> <%: Html.DisplayFor(modelItem => item.Gov) %></span> <span class="media">Tel : <%: Html.DisplayFor(modelItem => item.Telag) %> |</span> <%: Html.DisplayFor(modelItem => item.Mailag) %>
</div>
<div class="listingbtns">
<span class="listbuttons"><%: Html.ActionLink("Bloque", "Bloque", new {id= item.Idag}) %> </span>
<span class="listbuttons"><%: Html.ActionLink("Supprime", "DeleteAg", new { id = item.Idag })%></span>
</div>
<div class="clear">
</div>
</li>
<% } %>
i got this error : System.NullReferenceException: Object reference not set to an instance of an object on this line <% foreach (var item in Model) { %>.

Retrieve a subset of a ViewModel from a RenderPartial on POST

I have a ViewModel which contains a child ViewModel. In a strongly typed Viewed of the parent, I want to RenderPartial on the child, and have results persist following POST.
But the child fields are always null.
This should work, shouldn't it? I am fairly new to MVC, hopefully I'm missing something simple. Hopefully someone can point it out!
Thanks!
Example
ViewModels
public class EggBoxViewModel
{
public string Brand { get; set; }
public int Price { get; set; }
public EggViewModel Egg { get; set; }
}
public class EggViewModel
{
public string Size { get; set; }
public bool IsBroken { get; set; }
}
Controller
public ActionResult Demo()
{
EggBoxViewModel eggBox = new EggBoxViewModel();
eggBox.Brand = "HappyEggs";
eggBox.Price = 3;
EggViewModel egg = new EggViewModel();
egg.Size = "Large";
egg.IsBroken = false;
eggBox.Egg = egg;
return View(eggBox);
}
[HttpPost]
public ActionResult Demo(EggBoxViewModel eggBox)
{
// here, eggBox.Egg is null
}
Views
"Demo"
#model MvcApplication1.ViewModels.EggBoxViewModel
#using (Html.BeginForm())
{
<h2>EggBox:</h2>
<p>
#Html.LabelFor(model => model.Brand)
#Html.EditorFor(model => model.Brand)
</p>
<p>
#Html.LabelFor(model => model.Price)
#Html.EditorFor(model => model.Price)
</p>
<p>
#{Html.RenderPartial("_Egg", Model.Egg);}
</p>
<input type="submit" value="Submit" />
}
"_Egg" (Partial)
#model MvcApplication1.ViewModels.EggViewModel
<h2>Egg</h2>
<p>
#Html.LabelFor(model => model.Size)
#Html.EditorFor(model => model.Size)
</p>
<p>
#Html.LabelFor(model => model.IsBroken)
#Html.CheckBoxFor(model => model.IsBroken)
</p>
Use an Editor Template, in most cases they're better for rendering child objects or collections. In your Views\Shared folder create a new folder called EditorTemplates if you don't already have one. Add a new partial view called EggViewModel and use the same code as in your partial view. This is the bit of magic that renders and names all your fields correctly. It will also handle a collection of EggViewModels without a for each loop as the Editor template will automatically render all the items passed in a collection:
#model MvcApplication1.ViewModels.EggViewModel
<h2>Egg</h2>
<p>
#Html.LabelFor(model => model.Size)
#Html.EditorFor(model => model.Size)
</p>
<p>
#Html.LabelFor(model => model.IsBroken)
#Html.CheckBoxFor(model => model.IsBroken)
</p>
Then in your Demo View use your new Editor Template instead of the partial:
<p>
#Html.EditorFor(x => x.Egg)
</p>
Here are the fields that are rendered:
In the post back you can that the EggViewModel is now part of the EggBoxViewModel:
Also in the ModelState you can see that the Egg fields are prefixed with the property name used in the EggBoxViewModel which makes them a subset of EggBox.
And...the great thing is that if you want to have a collection of Eggs in your EggBox it's really easy...just make your Egg property on EggBoxViewModel a collection:
public class EggBoxViewModel
{
public string Brand { get; set; }
public int Price { get; set; }
public ICollection<EggViewModel> Eggs { get; set; }
}
Add a second egg:
public ActionResult Demo()
{
EggBoxViewModel eggBox = new EggBoxViewModel();
eggBox.Brand = "HappyEggs";
eggBox.Price = 3;
EggViewModel egg = new EggViewModel();
egg.Size = "Large";
egg.IsBroken = false;
EggViewModel egg2 = new EggViewModel();
egg2.Size = "Medium";
egg2.IsBroken = false;
eggBox.Eggs = new List<EggViewModel>();
eggBox.Eggs.Add(egg);
eggBox.Eggs.Add(egg2);
return View(eggBox);
}
Change your View to render x.Eggs instead of x.Egg:
<p>
#Html.EditorFor(x => x.Eggs)
</p>
Then on post back you'll see there are 2 Eggs posted back:
The field names have automatically been indexed and named to create a collection of Eggs:
you'll have to change your partial view model to EggBoxViewModel so that the Egg object is exposed on the view. i.e:
#model MvcApplication1.ViewModels.EggBoxViewModel
<h2>
Egg</h2>
<p>
#Html.LabelFor(model => model.Egg.Size)
#Html.EditorFor(model => model.Egg.Size)
</p>
<p>
#Html.LabelFor(model => model.Egg.IsBroken)
#Html.CheckBoxFor(model => model.Egg.IsBroken)
</p>
thus, you'd call it from the main view as:
#{Html.RenderPartial("_Egg", Model);}
you should now see the Egg object in your model being returned in the HttpPost action.
[Update method 2]
ok, really quick edit!! You can keep everything the same as initially and try this in your partial (i'm not 100% certain that this will work tho):
#model MvcApplication1.ViewModels.EggViewModel
<h2>
Egg</h2>
<p>
#Html.LabelFor(model => model.Size)
#Html.Editor("Egg.Size", Model.Size)
</p>
<p>
#Html.LabelFor(model => model.IsBroken)
#Html.CheckBox("Egg.IsBroken", Model.IsBroken)
</p>
here, I just use #Html.Editor() and input the required model name, rather than #Html.EditorFor(). Ok, gorra dash... train to 'cache' ;-)

html.dropdownlist MVC3 confusion

This works for me but how do I do the same thing using html.dropdownlist?
Notice that the value passed is not the value that is shown to the user.
#model IEnumerable<MVR.Models.ViewIndividual>
<h2>Level1</h2>
<select>
#foreach (var item in Model) {
<option value="#item.Case_Number">#item.Patient_Lastname ,
#item.Patient_Firstname
</option>
}
</select>
As always in an ASP.NET MVC application you start by defining a view model:
public class MyViewModel
{
public string SelectedIndividual { get; set; }
public SelectList Individuals { get; set; }
}
then you write a controller action that populates this view model from some data source or something:
public ActionResult Index()
{
// TODO : fetch those from your repository
var values = new[]
{
new { Value = "1", Text = "item 1" },
new { Value = "2", Text = "item 2" },
new { Value = "3", Text = "item 3" },
};
var model = new MyViewModel
{
Individuals = new SelectList(values, "Value", "Text")
};
return View(model);
}
and finally you have a strongly typed view using strongly typed helpers:
#model MyViewModel
#Html.DropDownListFor(
x => x.SelectedIndividual,
Model.Individuals
)
This being said, because I see that you are not using any view models in your application, you could always try the following ugliness (not recommended, do this at your own risk):
#model IEnumerable<MVR.Models.ViewIndividual>
<h2>Level1</h2>
#Html.DropDownList(
"SelectedIndividual",
new SelectList(
Model.Select(
x => new {
Value = x.Case_Number,
Text = string.Format(
"{0}, {1}",
x.Patient_Lastname,
x.Patient_Firstname
)
}
),
"Value",
"Text"
)
)
Of course such pornography is not something that I would recommend to ever write in a view and I wouldn't recommend even to my worst enemies.
Conclusion: In an ASP.NET MVC application you should always be using view models and strongly typed views with strongly typed helpers (see first part of my answer).
Here is the full example
public class PageModel
{
[Display(Name = "Page ID")]
public Guid ID { get; set; }
[Display(Name = "Page Type ID")]
public Guid PageTypeID { get; set; }
[Display(Name = "Title")]
public string Title { get; set; }
[Display(Name = "Page Type Name")]
public string PageTypeName { get; set; }
[Display(Name = "Html Content")]
public string HtmlContent { get; set; }
public SelectList PageTypeList { get; set; }
}
the C# code
public ActionResult Edit(Guid id)
{
var model = db.Pages.Where(p => p.ID == id).FirstOrDefault();
var typeList = new SelectList(db.PageTypes.OrderBy(s => s.Name).ToList(), "ID", "Name");
var viewModel = new PageModel { PageTypeList = typeList };
viewModel.HtmlContent = model.HtmlContent;
viewModel.ID = model.ID;
viewModel.PageTypeID = Guid.Parse(model.PageTypeID.ToString());
viewModel.Title = model.Title;
return View(viewModel);
}
[HttpPost]
[ValidateInput(false)]
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Edit(PageModel page)
{
if (ModelState.IsValid)
{
var model = db.Pages.Where(p => p.ID == page.ID).FirstOrDefault();
model.Title = page.Title;
model.HtmlContent = page.HtmlContent;
model.PageTypeID = page.PageTypeID;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(page);
}
and lastly html
#model competestreet.com.Models.PageModel
#{
ViewBag.Title = "Edit";
Layout = "~/Views/Shared/_LayoutCMS.cshtml";
}
<script type="text/javascript">
$(document).ready(function () {
$('#HtmlContent').ckeditor();
});
</script>
<script src="#Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/ckeditor/ckeditor.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/ckeditor/adapters/jquery.js")" type="text/javascript"></script>
<h2 class="title">
<span class="text-cms">CM<span>S</span></span></h2>
<div class="box">
<div class="t">
</div>
<div class="c">
<div class="content">
<div class="main-holder">
<div id="sidebar">
<ul>
<li>Home</li>
<li>Pages</li>
</ul>
</div>
<div id="content" style="min-height: 500px;">
#using (Html.BeginForm())
{
#Html.ValidationSummary(true)
<fieldset>
<legend>Page Type - #Html.DropDownListFor(x => x.PageTypeID, Model.PageTypeList)
#Html.ValidationMessageFor(model => model.PageTypeID)</legend>
<div class="editor-label">
#Html.LabelFor(model => model.Title)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Title, new { #class = "text-box" })
#Html.ValidationMessageFor(model => model.Title)
</div>
<div class="clear">
</div>
<div class="editor-label">
#Html.LabelFor(model => model.HtmlContent)
</div>
<div class="editor-field">
#Html.TextAreaFor(model => model.HtmlContent, new { #name = "Editor1", #class = "Editor1" })
#Html.ValidationMessageFor(model => model.HtmlContent)
</div>
<div class="clear">
</div>
<p>
<input type="submit" value="Save" class="input-btn" />
</p>
</fieldset>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
</div>
</div>
</div>
</div>
<div class="b">
</div>
</div>

Binding to an object with properties and a list

I've been able to bind a list of objects correctly. Works fine. Now when I change the item a complex object it stops working.
The complex object is the room name with the list of objects. When the 'postback' the name returns fine, but the list of objects comes back as null.
Any hints please?
Room Model:
public class Room
{
public string Name { get; set; }
public List<Option> Options { get; set; }
public Room() { }
public Room(string name, List<Option> options)
{
Name = name; Options = options;
}
}
Options Model
public class Option
{
public bool IsSelected { get; set; }
public string ImagePath { get; set; }
public int UniqueID { get; set; }
public Option() { }
public Option(bool isSelected, string imagePath, int uniqueID)
{ IsSelected = isSelected; ImagePath = imagePath; UniqueID = uniqueID; }
}
HomeController
public ActionResult Index()
{
List<Option> options = new List<Option>();
options.Add(new Option(true, "../Content/cars_2.jpg", 4));
options.Add(new Option(true, "../Content/vw_one_liter_concept01_2.jpg", 6));
options.Add(new Option(false, "../Content/00018578.jpg", 8));
//Get a list of selected options and union with all remaining
Room model = new Room("Room1", options);
return View(model);
}
[HttpPost]
public ActionResult Index(Room model)
{
ViewData["results"] = model.Options.Count();
return View(model);
}
Index View
<%# Page Language="C#" Inherits="System.Web.Mvc.ViewPage<MultiSelect.Models.Room>" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Index</title>
<script src="../../Scripts/jquery-1.4.1.js" type="text/javascript"></script>
<script src="../../Scripts/jquery-ui-1.8.10.custom.min.js" type="text/javascript"></script>
</head>
<body>
<% using (Html.BeginForm())
{%>
<%= Html.ValidationSummary(true)%>
<%= Html.TextBoxFor(m=> m.Name) %>
<% Html.RenderPartial("MultiSelect", Model.Options); %>
<% } %>
</body>
</html>
MultiSelect Partial View
<%# Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<IList<MultiSelect.Models.Option>>" %>
<% for (int counter = 0;counter< Model.Count(); counter ++)
{ %>
<div class="opt">
<%= Html.HiddenFor(i=> i[counter].UniqueID)%>
<%= Html.HiddenFor(i=> i[counter].ImagePath) %>
<%= Html.CheckBoxFor(i => i[counter].IsSelected)%>
<img src="<%= Model.ElementAt(counter).ImagePath %>" alt="Image" width="128" height="128" />
</div>
<% } %>
<input id="Submit1" type="submit" value="submit" />
http://blog.stevensanderson.com/2010/01/28/editing-a-variable-length-list-aspnet-mvc-2-style/ provides a solution for what you're looking for.
Alternatively, an easier, but less flexible solution is to put a Room.cshtml file, and a Option.cshtml file in your Shared/EditorTemplates folder. Then you'd put
<%= Html.TextBoxFor(m=> m.Name) %>
<% Html.EditorFor(m => m.Options); %>
in Room.cshtml
<% Html.EditorFor(m => Model); %>
in index, and the contents of your partial view in Option.cshtml.

ModelState.IsValid returns false when it should be true

I have a pretty simple MVC 2 form. It has two dropdowns, user and role. The employee dropdown passes validation, and the role dropdown does not, regardless of what I select. There is no default "empty" option although I plan to implement one, which is why I need the validation to work. It fails both client and server validation. I just can't see why one would work and one does not!
The Form:
<% using (Html.BeginForm()) {%>
<%:Html.ValidationSummary(true) %>
<%:Html.EditorFor(model => model.User, new { AllEmployees = Model.AllEmployees, RoleList = Model.RoleList })%>
<p>
<input type="submit" value="Add New User" />
</p>
<% } %>
<% Html.EndForm(); %>
The Editor Template:
<tr>
<td>
<div class="editor-label">
<%: Html.LabelFor(model => model.UserId) %>
<%: Html.RequiredMarkFor(model => model.UserId) %>
</div>
</td>
<td>
<div class="editor-field">
<%: Html.DropDownListFor(model => model.UserId, new SelectList(ViewData["AllEmployees"] as IEnumerable, "UserId", "DisplayName", Model.UserId)) %>
<%: Html.ValidationMessageFor(model => model.UserId>
</div>
</td>
</tr>
<tr>
<td>
<div class="editor-label">
<%: Html.LabelFor(model => model.AccessLevel)%>
<%: Html.RequiredMarkFor(model => model.AccessLevel)%>
</div>
</td>
<td>
<div class="editor-field">
<%: Html.DropDownListFor(model => model.AccessLevel, new SelectList(ViewData["RoleList"] as IEnumerable, Model.AccessLevel))%>
<%: Html.ValidationMessageFor(model => model.AccessLevel)%>
</div>
</td>
</tr>
The Metadata:
[DisplayName("Employee")]
[Required(ErrorMessage = "Please select an employee.")]
[StringLength(8, ErrorMessage = "User Id must be less than 8 characters.")]
[DisplayFormat(ConvertEmptyStringToNull = false,
HtmlEncode = true)]
[DataType(DataType.Text)]
public object UserId { get; set; }
// Validation rules for Access Level
[DisplayName("Role")]
[Required(ErrorMessage = "Please select the role for this user.")]
[StringLength(15, ErrorMessage = "Role must be under 15 characters.")]
[DisplayFormat(ConvertEmptyStringToNull = false,
HtmlEncode = true)]
[DataType(DataType.Text)]
public object AccessLevel { get; set; }
The Get Action:
List<String> roles = (from o in txDB.Users
select o.AccessLevel).Distinct().ToList();
var viewModel = new UserViewModel
{
User = new User(),
AllEmployees = empList,
RoleList = roles
};
return View(viewModel);
The Post Action:
[HttpPost]
[AuthorizeAttribute(Roles="Administrator")]
public ActionResult Create(User user)
{
if(!ModelState.IsValid)
{
//ModelState is invalid
return View(new User());
}
try
{
//do stuff
}
}
The Required Helper Method (from Define markup for [Required] fields in View in ASP.NET MVC 2.0):
public static string RequiredMarkFor<TModel, TProperty>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TProperty>> expression)
{
if(ModelMetadata.FromLambdaExpression(expression, helper.ViewData).IsRequired)
return "*";
else
return string.Empty;
}
Post method should be as follows to get Server side validation...
[HttpPost]
[AuthorizeAttribute(Roles="Administrator")]
public ActionResult Create(User user)
{
if(!TryUpdateModel(user))
{
// Model is INVALID
return View(user);
}
else
{
// ModelState is VALID
// Do stuff
}
}
The else might be redundant depending on what you're doing but that should get you going.
In the view above your <% using Html.BeginForm() %> you need
<% Html.EnableClientValidation(); %>
You also need to reference the scripts, MicrosoftAjax and MicrosoftMvcValidation I think
First of all: You have two closing form tags
If you use
<% using (Html.BeginForm()) {%>
<% } %>
you dont need to use this
<% Html.EndForm(); %>
Regarding your validation problem you are using an editor only for your User property, which is the only one that get binded by the model binder
<%:Html.EditorFor(model => model.User, new { AllEmployees = Model.AllEmployees, RoleList = Model.RoleList })%>
Try to replace the previous code with an EditorForModel as your Editor Template is for a model class.
So your form should change in
<% using (Html.BeginForm()) {%>
<%:Html.ValidationSummary(true) %>
<table>
<%:Html.EditorForModel()%>
</table>
<p>
<input type="submit" value="Add New User" />
</p>
<% } %>
and you're done!

Resources