Create button click function not working in mvc3? - asp.net-mvc-3

Hi guys i have a table where i have a add new project link ...when i click on that it takes me to a create page where i have textboxes for inserting new record and a button to create..but i click on create button its not working can any one help me where am i doing wrong here is my code
This is my create.aspx page:
<%: ViewBag.Title="Create" %>
<fieldset>
<legend>Projects</legend>
<div class="editor-label">
<%: Html.LabelFor(model => model.projectName)%>
</div>
<div class="editor-field">
<%:Html.EditorFor(model => model.projectName)%>
<%: Html.ValidationMessageFor(model => model.projectName)%>
</div>
<div class="editor-label">
<%:Html.LabelFor(model => model.Description)%>
</div>
<div class="editor-field">
<%:Html.EditorFor(model => model.Description)%>
<%:Html.ValidationMessageFor(model => model.Description)%>
</div>
<div class="editor-label">
<%:Html.LabelFor(model=>model.status) %>
</div>
<div class="editor-field">
<%:Html.EditorFor(model=>model.status) %>
<%:Html.ValidationMessageFor(model=>model.status) %>
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
And this is my controller function:
public ActionResult Create()
{
return View();
}
[HttpPost]
public ActionResult Create(ProjectModel model)
{
var modelList = new List<ProjectModel>();
using (SqlConnection conn = new SqlConnection("Data Source=LMIT-0039;Initial Catalog=BugTracker;Integrated Security=True"))
{
conn.Open();
SqlCommand insertcommande = new SqlCommand("Sp_AddNewProject", conn);
insertcommande.CommandType = CommandType.StoredProcedure;
insertcommande.Parameters.Add("#ProjectName", SqlDbType.VarChar).Value = model.projectName;
insertcommande.Parameters.Add("#Description", SqlDbType.VarChar).Value = model.Description;
insertcommande.Parameters.Add("#Status", SqlDbType.VarChar).Value = model.status;
insertcommande.ExecuteNonQuery();
}
return View( modelList);
}
when i click on create button in aspx page it should go to create method in my controller .....what am i doing wrong here.........

I put this in my create.aspx page BeginForm statement:
<% using (Html.BeginForm()) { %>
<form action=”/members/Create” method=”post”></form>
and added
[AcceptVerbs(HttpVerbs.Get)]
public ActionResult Create()
{
return View();
}
[AcceptVerbs(HttpVerbs.post)]
public ActionResult Create(ProjectModel model)
{
var modelList = new List<ProjectModel>();
using (SqlConnection conn = new SqlConnection("Data Source=LMIT-0039;Initial Catalog=BugTracker;Integrated Security=True"))
{
conn.Open();
SqlCommand insertcommande = new SqlCommand("Sp_AddNewProject", conn);
insertcommande.CommandType = CommandType.StoredProcedure;
insertcommande.Parameters.Add("#ProjectName", SqlDbType.VarChar).Value = model.projectName;
insertcommande.Parameters.Add("#Description", SqlDbType.VarChar).Value = model.Description;
insertcommande.Parameters.Add("#Status", SqlDbType.VarChar).Value = model.status;
insertcommande.ExecuteNonQuery();
}
return View( modelList);
}

There is no form in your View. That is one problem.

Visit MSDN for BeginForm: http://msdn.microsoft.com/en-us/library/dd410596.aspx

Related

ajax post double triggers each time sending form

i working with asp.net mvc5 and trying to post a form to the controller without refreshing the page using ajax. but the problem is that each time i press the submit button, it sends the data many times. only the first time it submits the form once. but the second time it send twice, and the third time it sends four times and ...
here is my controller
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using UniProject.Models;
namespace UniProject.Controllers
{
public class TestController : Controller
{
MyContext db = new MyContext();
// GET: Test
[HttpGet]
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult Create(Test test)
{
try
{
if (ModelState.IsValid)
{
db.Tests.Add(test);
db.SaveChanges();
ViewBag.Record = "Data Inserted";
return PartialView("Index");
}
else
{
ViewBag.Record = "Error";
return View(test);
}
}
catch
{
ViewBag.Record = "Error";
return View();
}
}
}
}
this is my view
#model UniProject.Models.Test
#{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<script src="~/Scripts/jquery-1.10.2.js"></script>
<script src="~/Scripts/jquery.unobtrusive-ajax.min.js"></script>
<h2>Index</h2>
<div id="div">
#Html.Partial("Form" , Model)
</div>
<div>
#Html.ActionLink("Back to List", "Index")
</div>
My PartialView
#model UniProject.Models.Test
#using (Ajax.BeginForm("Create" , "Test" , new AjaxOptions { HttpMethod = "post" , UpdateTargetId = "div"}))
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Test</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.TestName, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.TestName, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.TestName, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.TestTitle, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.TestTitle, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.TestTitle, "", 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>
}
this the form view after once clicking submit button
Form Image
and this is the database image
Database Records
please help me with this issue. thanks in advance...

Entity framework update shows dbconcurrency while updating a record?

in my code the update takes place both in the view and in the controller. Same Controller and View for both create and Update. Create profile works fine. but while updating it shows DbConcurrency exception Message. Please help me to find.
Exception Message while updating the record:
Store update, insert, or delete statement affected an unexpected number of rows (0). Entities may have been modified or deleted since entities were loaded. Refresh ObjectStateManager entries.
My Update profile page has (Profile.cshtml)
#model Sitecss.Models.Profile
#using Microsoft.Web.Helpers;
#{
ViewBag.Title = "CreateProfile";
Layout = "~/Views/Shared/_HomeLay.cshtml";
}
#{
var GT = new SelectList(new[] {
new {ID ="Team DeathMatch", Name="Team DeathMatch"},
new {ID ="Search & Destroy", Name="Search & Destroy"},
new {ID ="Flag Runner", Name="Flag Runner"},
new {ID ="Domination", Name="Domination"},
new {ID ="Kill Confirmed", Name="Kill Confirmed"}
},"ID","Name");
var Spec = new SelectList(new []{
new {ID ="Assault", Name="Assault"},
new {ID ="Tactical", Name="Tactical"},
new {ID ="Long-Range Eliminations", Name="Long-Range Eliminations"},
new {ID ="Noob", Name="Noob"}
}, "ID", "Name");
}
<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>
#using (Html.BeginForm("CreateProfile", "Home", FormMethod.Post, new { #encType = "multipart/form-data" }))
{
<div id="content1">
#Html.ValidationSummary(true)
<h4>Create a Profile</h4>
<div>
#Html.LabelFor(m => m.SteamName)
</div>
<div>
#Html.TextBoxFor(m => m.SteamName, new { #class = "wide" })
#Html.ValidationMessageFor(m => m.SteamName)
</div>
<div>
#Html.LabelFor(m =>m.UserImg)
</div>
<div>
<input type="file" name="image" class="image" /> <br />
</div>
<div>
#Html.LabelFor(m => m.GameType)
</div>
<div>
#Html.DropDownListFor(m => m.GameType, GT, new { #class = "wide" })
#Html.ValidationMessageFor(m => m.GameType)
</div>
<div>
#Html.LabelFor(m => m.Specialist)
</div>
<div>
#Html.DropDownListFor(m => m.Specialist, Spec, new { #class = "wide" })
#Html.ValidationMessageFor(m => m.Specialist)
</div>
<div>
#Html.LabelFor(m => m.FavGun)
</div>
<div>
#Html.TextBoxFor(m => m.FavGun, new { #class = "wide" })
#Html.ValidationMessageFor(m => m.FavGun)
</div>
<p><input type="submit" class="button" value="Ok" /></p>
</div>
}
while my controller functions are
public ActionResult CreateProfile()
{
if (db.Profiles.Any(u => u.Username == User.Identity.Name))
{
Profile pro = (from usr in db.Profiles where usr.Username == User.Identity.Name select usr).Single();
olf = pro.UserImg;
Profile p = db.Profiles.Find(pro.Id);
ViewBag.ProfilePic = olf;
return View(p);
}
else
{
ViewBag.Name = User.Identity.Name;
return View();
}
}
[HttpPost]
public ActionResult CreateProfile(Profile m)
{
WebImage photo = WebImage.GetImageFromRequest();
string newFileName = "";
string thumbs = "";
if (photo != null)
{
string ext = Path.GetExtension(photo.FileName);
newFileName = User.Identity.Name+ ext;
thumbs = #"Images/" + newFileName;
photo.Resize(width: 120, height: 120, preserveAspectRatio: true, preventEnlarge: true);
photo.Save(#"~/"+thumbs);
m.UserImg = newFileName;
}
if (ModelState.IsValid)
{
if (db.Profiles.Any(u => u.Username == User.Identity.Name))
{
db.Entry(m).State = System.Data.EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
else
{
m.Username = User.Identity.Name;
db.Profiles.Add(m);
db.SaveChanges();
return RedirectToAction("Index");
}
}
return View(m);
}
While Adding Breakpoint to the update statement in my edit Controller I came to know that the primary key Id =0 on update in order to fix this issue I have added Hidden Field in the view that has fixed the DbConcurrency on update

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) { %>.

ado.net mvc3 tuple using in model and single views

I have the following ADO Model
Student
Id,Name
and
Course
Id,Name,Student_ID
I have made the following view for it
#model Tuple<MvcApplication4.Models.Course, MvcApplication4.Models.Student >
#{
ViewBag.Title = "Create";
}
<h2>Create</h2>
#using (Html.BeginForm()) {
#Html.ValidationSummary(true)
<fieldset>
<legend>Course</legend>
<div class="editor-label">
#Html.LabelFor(model => model.Item1.Name)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Item1.Name)
#Html.ValidationMessageFor(model => model.Item1.Name)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Item1.S_ID, "Student")
</div>
<fieldset>
<legend>Student</legend>
<div class="editor-label">
#Html.LabelFor(model => model.Item2.Name)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Item2.Name)
#Html.ValidationMessageFor(model => model.Item2.Name)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Item2.Class)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Item2.Class)
#Html.ValidationMessageFor(model => model.Item2.Class)
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
</fieldset>
}
And the controller for it is as
public ActionResult Create()
{
return View();
}
//
// POST: /Default3/Create
[HttpPost]
public ActionResult Create(Tuple<Student ,Course > t)
{
try
{
// TODO: Add insert logic here
db.Students.AddObject(t.Item1);
db.SaveChanges();
t.Item2.S_ID = t.Item1.Id;
db.Courses.AddObject(t.Item2);
db.SaveChanges();
return RedirectToAction("Copy");
}
catch
{
return View();
}
}
But When i click the Creat button it gives the following Error
Server Error in '/' Application.
No parameterless constructor defined for this object.
The Tuple<X, Y> class doesn't have a default constructor so you will need to write a custom model binder if you want this to work. Another possibility is to use a custom view model which is what I would recommend you:
public class MyViewModel
{
public Course Course { get; set; }
public Student Student { get; set; }
}
and then:
public ActionResult Create()
{
return View(new MyViewModel());
}
//
// POST: /Default3/Create
[HttpPost]
public ActionResult Create(MyViewModel model)
{
try
{
// TODO: Add insert logic here
db.Students.AddObject(t.Student);
db.SaveChanges();
t.Course.S_ID = t.Student.Id;
db.Courses.AddObject(t.Course);
db.SaveChanges();
return RedirectToAction("Copy");
}
catch
{
return View(model);
}
}
and finally:
#model MvcApplication4.Models.MyViewModel
#{
ViewBag.Title = "Create";
}
<h2>Create</h2>
#using (Html.BeginForm()) {
#Html.ValidationSummary(true)
<fieldset>
<legend>Course</legend>
<div class="editor-label">
#Html.LabelFor(model => model.Student.Name)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Student.Name)
#Html.ValidationMessageFor(model => model.Student.Name)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Student.S_ID, "Student")
</div>
<fieldset>
<legend>Student</legend>
<div class="editor-label">
#Html.LabelFor(model => model.Course.Name)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Course.Name)
#Html.ValidationMessageFor(model => model.Course.Name)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Course.Class)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Course.Class)
#Html.ValidationMessageFor(model => model.Course.Class)
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
MVC is pretty smart, but it can't really figure out how to create a new instance of Tuple and create new instances of the items, then assign the proper items to it. That's just too complex of a task.
The error you get is because a Tuple doesn't have a default parameterless constructor, and requires new items to be passed to it in the constructor, something that MVC can't do.
You will have to break this down, and create your tuple in your controller action from a viewmodel that contains your items as members.
You need to pass the model to your view.
Example:
return View(model);
This seems to have resolved the issue for me as an alternative and it is working now:
[HttpGet]
public ActionResult Create()
{
Course course = new Course();
Student student = new Student();
var tuple = new Tuple<Course,Student>(course,student);
return View(tuple);
}
[HttpPost]
public ActionResult Create(Tuple<Course,Student> tuple){ do something ...}
I tried several other approaches include some that have been suggested here but, didn't resolve the problem. I just posted this to help someone else who might want to use Tuple though, use it only if you don't have another alternative.
I got it to work after a few minutes of digging and some thinking. Here's a quick example of what I did:
GET action:
[HttpGet]
public ActionResult Update(int id = 0)
{
ProductDto product = _productService.FindByID(id);
SupplierDto supplier = _supplierService.FindByProductID(productId: product.ProductID);
return View(model: new Tuple<ProductDto, SupplierDto>(product, supplier));
}
POST action:
[HttpPost]
public JsonResult Update(int id = 0, ProductDto Item1, SupplierDto Item2)
{
// Get the product name
string productName = Item1.ProductName;
// Get the supplier name
string supplierName = Item2.SupplierName;
...
return Json(new { success = true });
}
View:
#model Tuple<ProductDto, SupplierDto>
#{
ViewBag.Title = "add title later ... ";
AjaxOptions options = new AjaxOptions { ... };
}
#using (Ajax.BeginForm("Update", "Product", options, htmlAttributes: new { #id = "update-form" }))
{
<fieldset>
<legend>Update Product</legend>
<div class="display-label">
#Html.LabelFor(model => model.Item1.ProductName)
</div>
<div class="display-field">
#Html.EditorFor(model => model.Item1.ProductName)
</div>
...
<div class="display-label">
#Html.LabelFor(model => model.Item2.SupplierName)
</div>
<div class="display-field">
#Html.EditorFor(model => model.Item2.SupplierName)
</div>
</fieldset>
<div class="submit-button">
<button type="submit" class="button">Update details</button>
<div>
}
You should bind prefix in parameters
Controller:
public ActionResult ThisMethod([Bind(Prefix = "Item1")] AccountViewModel model)
{
// toDo
}
View:
#model Tuple<AccountViewModel>
#Html.EditorFor(model => model.Item1.Firstname)
#DarinDimitri's solution is right but there is a way with Tuple as well. If you just change these code below you will get tuple models.
[HttpPost]
public ActionResult Create(Course Item1, Student Item2)
{
try
{
// TODO: Add insert logic here
db.Students.AddObject(Item2);
db.SaveChanges();
Item1.S_ID = Item2.Id;
db.Courses.AddObject(Item1);
db.SaveChanges();
return RedirectToAction("Copy");
}
catch
{
return View();
}

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