Uploading Image in Asp.net mvc Controller - asp.net-mvc

I have a Upload form and I want to pass my information such as an Image and some other field but I don't know how can I upload Image ..
This is My model class
public partial class NewProductCategory
{
public string ProductName { get; set; }
public string ProductDescription { get; set; }
public string ProductPrice { get; set; }
public string ProductImage { get; set; }
public string ProductQuantity { get; set; }
public Nullable<bool> ProductStatus { get; set; }
public Nullable<int> CategoryId { get; set; }
public HttpPostedFileBase user_image_data { get; set; }
public virtual Category Category { get; set; }
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(NewProductCategory productcategory, HttpPostedFileBase file)
{
if (ModelState.IsValid)
{
ProductCategory newproductCategory = new ProductCategory();
string path = Path.Combine(Server.MapPath("~/Content/files"), Path.GetFileName(file.FileName));
file.SaveAs(path);
newproductCategory.ProductDescription = productcategory.ProductDescription;
newproductCategory.ProductQuantity = productcategory.ProductQuantity;
newproductCategory.ProductStatus = productcategory.ProductStatus;
newproductCategory.CategoryId = productcategory.CategoryId;
db.ProductCategories.Add(newproductCategory);
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.CategoryId = new SelectList(db.Categories, "CategoryId", "Name", productcategory.CategoryId);
return View(productcategory);
}
And this is My View Code
#model MvcApplication1.Models.NewProductCategory
#{
ViewBag.Title = "Create";
}
<h2>Create</h2>
#using (Html.BeginForm()) {
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
<fieldset>
<legend>ProductCategory</legend>
#using (Html.BeginForm("Create", "Temp", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<div class="editor-label">
#Html.LabelFor(model => model.ProductName)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.ProductName)
#Html.ValidationMessageFor(model => model.ProductName)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.ProductDescription)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.ProductDescription)
#Html.ValidationMessageFor(model => model.ProductDescription)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.ProductPrice)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.ProductPrice)
#Html.ValidationMessageFor(model => model.ProductPrice)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.user_image_data)
</div>
<div class="editor-label">
#Html.Label("Upload your image")
</div>
<div class="editor-field">
#Html.TextBoxFor(model => model.user_image_data, new { Type = "File" })
#Html.ValidationMessageFor(model => model.user_image_data)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.ProductQuantity)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.ProductQuantity)
#Html.ValidationMessageFor(model => model.ProductQuantity)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.ProductStatus)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.ProductStatus)
#Html.ValidationMessageFor(model => model.ProductStatus)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.CategoryId, "Category")
</div>
<div class="editor-field">
#Html.DropDownList("CategoryId", String.Empty)
#Html.ValidationMessageFor(model => model.CategoryId)
</div>
<p>
<input type="submit" value="Create" />
</p>
}
</fieldset>
}
please help me in controller i am getting Null value for File upload

Update Ansawer
#model MvcApplication1.Models.NewProductCategory
#{
ViewBag.Title = "Create";
}
#using (Html.BeginForm("Create", "Temp", FormMethod.Post, new { enctype = "multipart/form-data" }))
{ #Html.AntiForgeryToken()
#Html.ValidationSummary(true)
<fieldset>
<legend>ProductCategory</legend>
<div class="editor-label">
#Html.LabelFor(model => model.ProductName)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.ProductName)
#Html.ValidationMessageFor(model => model.ProductName)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.ProductDescription)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.ProductDescription)
#Html.ValidationMessageFor(model => model.ProductDescription)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.ProductPrice)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.ProductPrice)
#Html.ValidationMessageFor(model => model.ProductPrice)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.user_image_data)
</div>
<div class="editor-field">
#Html.TextBoxFor(model => model.user_image_data, new { Type = "File" })
#Html.ValidationMessageFor(model => model.user_image_data)
</div>
<div class="editor-label">
#Html.Label("Upload your image")
</div>
<div class="editor-label">
#Html.TextBox("file",null,htmlAttributes: new { Type = "file" })
</div>
<div class="editor-label">
#Html.LabelFor(model => model.ProductQuantity)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.ProductQuantity)
#Html.ValidationMessageFor(model => model.ProductQuantity)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.ProductStatus)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.ProductStatus)
#Html.ValidationMessageFor(model => model.ProductStatus)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.CategoryId, "Category")
</div>
<div class="editor-field">
#Html.DropDownList("CategoryId", String.Empty)
#Html.ValidationMessageFor(model => model.CategoryId)
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}

Related

View returns null value when using two models in MVC

I have a simple MVC program where earlier I was using one model and the code was working fine. here is the code.
View
#model Microsoft.Azure.ActiveDirectory.GraphClient.User
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Create User</title>
</head>
<body>
<h2>Create User</h2><br />
#using (Html.BeginForm("Create",
"CreateUsers",
new { id = Model != null ? Model.ObjectId : "" },
FormMethod.Post,
new { enctype = "multipart/form-data" })
)
{
<fieldset>
<legend>User</legend>
<div class="editor-label">
#Html.LabelFor(model => model.UserPrincipalName)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.UserPrincipalName)
#Html.ValidationMessageFor(model => model.UserPrincipalName)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.AccountEnabled)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.AccountEnabled)
#Html.ValidationMessageFor(model => model.AccountEnabled)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.PasswordProfile.Password)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.PasswordProfile.Password)
#Html.ValidationMessageFor(model => model.PasswordProfile.Password)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.MailNickname)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.MailNickname)
#Html.ValidationMessageFor(model => model.MailNickname)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.DisplayName)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.DisplayName)
#Html.ValidationMessageFor(model => model.DisplayName)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.GivenName)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.GivenName)
#Html.ValidationMessageFor(model => model.GivenName)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Surname)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Surname)
#Html.ValidationMessageFor(model => model.Surname)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.JobTitle)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.JobTitle)
#Html.ValidationMessageFor(model => model.JobTitle)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Department)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Department)
#Html.ValidationMessageFor(model => model.Department)
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
</body>
</html>
#if (ViewBag.ErrorMessage == "AuthorizationRequired")
{
<p>You have to sign-in. Click #Html.ActionLink("here", "Create", "Users", new { reauth = true }, null) to sign-in.</p>
}
Controller
public async Task<ActionResult> Create(string blobDetails)
{
#region POPULATE USER DETAIL IN CREATEUSER FIELDS
List<string> userDetails = blobDetails.Split(',').ToList();
User user = new User();
user.UserPrincipalName = userDetails[2] + "#xxx.com";
user.GivenName = userDetails[0];
user.Surname = userDetails[1];
user.DisplayName = userDetails[0] + " " + userDetails[1];
return View(Tuple.Create(user);
#endregion
}
[HttpPost]
public async Task<ActionResult> Create([Bind(Include ="UserPrincipalName,AccountEnabled,PasswordProfile,MailNickname,DisplayName,GivenName,Surname,JobTitle,Department")] User user)
{
ActiveDirectoryClient client = null;
client = AuthenticationHelper.GetActiveDirectoryClient();
string name = user.GivenName;
string username = user.UserPrincipalName;
return RedirectToAction("Index");
}
And this works perfectly fine , I get the values of user.GivenName and user.UserPrincipalName from view and I store it into string. Now what I am doing is that I am including one more model into this and trying to get its value from view so I did something like this:
Model
public class CreateUsers
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string Email { get; set; }
public string PhoneNumber { get; set; }
public string PIDetails { get; set; }
public string BlobDetails { get; set; }
public string UserEmail { get; set; }
}
View
#using WebAppGraphAPI.Models
#model Tuple<Microsoft.Azure.ActiveDirectory.GraphClient.User, CreateUsers>
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Create User</title>
</head>
<body>
<h2>Create User</h2><br />
#using (Html.BeginForm("Create",
"CreateUsers",
new { id = Model != null ? Model.Item1.ObjectId : ""
},
FormMethod.Post,
new { enctype = "multipart/form-data" })
)
{
#Html.ValidationSummary(true)
<fieldset>
<legend>User</legend>
<div class="editor-label">
#Html.LabelFor(tuple => tuple.Item1.UserPrincipalName)
</div>
<div class="editor-field">
#Html.EditorFor(tuple => tuple.Item1.UserPrincipalName)
#Html.ValidationMessageFor(tuple => tuple.Item1.UserPrincipalName)
</div>
<div class="editor-label">
#Html.LabelFor(tuple => tuple.Item1.AccountEnabled)
</div>
<div class="editor-field">
#Html.EditorFor(tuple => tuple.Item1.AccountEnabled)
#Html.ValidationMessageFor(tuple => tuple.Item1.AccountEnabled)
</div>
<div class="editor-label">
#Html.LabelFor(tuple => tuple.Item1.PasswordProfile.Password)
</div>
<div class="editor-field">
#Html.EditorFor(tuple => tuple.Item1.PasswordProfile.Password)
#Html.ValidationMessageFor(tuple => tuple.Item1.PasswordProfile.Password)
</div>
<div class="editor-label">
#Html.LabelFor(tuple => tuple.Item1.MailNickname)
</div>
<div class="editor-field">
#Html.EditorFor(tuple => tuple.Item1.MailNickname)
#Html.ValidationMessageFor(tuple => tuple.Item1.MailNickname)
</div>
<div class="editor-label">
#Html.LabelFor(tuple => tuple.Item1.DisplayName)
</div>
<div class="editor-field">
#Html.EditorFor(tuple => tuple.Item1.DisplayName)
#Html.ValidationMessageFor(tuple => tuple.Item1.DisplayName)
</div>
<div class="editor-label">
#Html.LabelFor(tuple => tuple.Item1.GivenName)
</div>
<div class="editor-field">
#Html.EditorFor(tuple => tuple.Item1.GivenName)
#Html.ValidationMessageFor(tuple => tuple.Item1.GivenName)
</div>
<div class="editor-label">
#Html.LabelFor(tuple => tuple.Item1.Surname)
</div>
<div class="editor-field">
#Html.EditorFor(tuple => tuple.Item1.Surname)
#Html.ValidationMessageFor(tuple => tuple.Item1.Surname)
</div>
<div class="editor-label">
#Html.LabelFor(tuple => tuple.Item1.JobTitle)
</div>
<div class="editor-field">
#Html.EditorFor(tuple => tuple.Item1.JobTitle)
#Html.ValidationMessageFor(tuple => tuple.Item1.JobTitle)
</div>
<div class="editor-label">
#Html.LabelFor(tuple => tuple.Item1.Department)
</div>
<div class="editor-field">
#Html.EditorFor(tuple => tuple.Item1.Department)
#Html.ValidationMessageFor(tuple => tuple.Item1.Department)
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
<div class="editor-label">
#*#Html.LabelFor(tuple => tuple.Item2.UserEmail)*#
#Html.EditorFor(tuple => tuple.Item2.UserEmail)
</div>
</body>
</html>
#if (ViewBag.ErrorMessage == "AuthorizationRequired")
{
<p>You have to sign-in. Click #Html.ActionLink("here", "Create", "Users", new { reauth = true }, null) to sign-in.</p>
}
Controller
public async Task<ActionResult> Create(string blobDetails)
{
#region POPULATE USER DETAIL IN CREATEUSER FIELDS
List<string> userDetails = blobDetails.Split(',').ToList();
User user = new User();
user.UserPrincipalName = userDetails[2] + "#gwuadmeaoutlook.onmicrosoft.com";
user.GivenName = userDetails[0];
user.Surname = userDetails[1];
user.DisplayName = userDetails[0] + " " + userDetails[1];
CreateUsers userInfo = new CreateUsers();
userInfo.UserEmail = userDetails[4];
return View(Tuple.Create(user,userInfo));
}
[HttpPost]
public async Task<ActionResult> Create([Bind(Include ="UserPrincipalName,AccountEnabled,PasswordProfile,MailNickname,DisplayName,GivenName,Surname,JobTitle,Department")] User user,[Bind(Include ="UserEmail")] CreateUsers userInfo)
{
ActiveDirectoryClient client = null;
client = AuthenticationHelper.GetActiveDirectoryClient();
string name = user.GivenName;
string username = user.UserPrincipalName;
string Email = userInfo.UserEmail
return RedirectToAction("Index");
}
When I do this I do not get values from View in my controller strings , it shows null. Can you suggest me how can I achieve this.
You could use an object which contains all of the properties you're trying to send to the client. We generally create DTOs for this specific usage. In you're case you'd have:
CreateDto
public class CreateDto
{
public Microsoft.Azure.ActiveDirectory.GraphClient.User User { get; set; }
public CreateUsers UserInfo { get; set; }
}
Then you're controller will be updated as:
public async Task<ActionResult> Create(string blobDetails)
{
#region POPULATE USER DETAIL IN CREATEUSER FIELDS
List<string> userDetails = blobDetails.Split(',').ToList();
User user = new User();
user.UserPrincipalName = userDetails[2] + "#gwuadmeaoutlook.onmicrosoft.com";
user.GivenName = userDetails[0];
user.Surname = userDetails[1];
user.DisplayName = userDetails[0] + " " + userDetails[1];
CreateUsers userInfo = new CreateUsers();
userInfo.UserEmail = userDetails[4];
var dto = new CreateDto() {
User = user,
UserInfo = userInfo
}
return View(dto);
}
[HttpPost]
public async Task<ActionResult> Create([Bind(Include ="UserPrincipalName,AccountEnabled,PasswordProfile,MailNickname,DisplayName,GivenName,Surname,JobTitle,Department")] User user,[Bind(Include ="UserEmail")] CreateUsers userInfo)
{
ActiveDirectoryClient client = null;
client = AuthenticationHelper.GetActiveDirectoryClient();
string name = user.GivenName;
string username = user.UserPrincipalName;
string Email = userInfo.UserEmail
return RedirectToAction("Index");
}
And your view will have:
#using WebAppGraphAPI.Models
#model CreateDto
Later you can reference the information with Model.user and Model.userInfo.
I know this doesn't explain why the Tuple doesn't work. I believe that is best explain by #darin-dimitrov in ado.net mvc3 tuple using in model and single views

ViewModel does not populate input fields

I have a ViewModel that is used for an edit View. When the data is returned, the ID of the item to be edited does not display on the edit View.
public ActionResult Edit(int id)
{
Parcel parcel = _parcelDao.GetParcel(id);
ParcelEditViewModel viewModel = new ParcelEditViewModel();
viewModel.id = parcel.id;
return View(viewModel);
}
Should I be returning something different to the View?
ViewModel:
public class ParcelEditViewModel
{
public Parcel parcel { get; set; }
public int id { get; set; }
public IEnumerable<SelectListItem> TrackStatus { get; set; }
public ParcelEditViewModel()
{
parcel = new Parcel();
TrackStatus = new List<SelectListItem>
{
new SelectListItem
{
Value = "AwaitingCollection",
Text = "Awaiting Collection"
},
new SelectListItem
{
Value = "OutForDelivery",
Text = "Out For Delivery"
},
new SelectListItem
{
Value = "Delivered",
Text = "Delivered"
}
};
}
public int ParcelStatus { get; set; }
}
View:
//#model ABC.Data.Parcel
#model Abc.ViewModels.ParcelEditViewModel
#{
ViewBag.Title = "Edit";
}
<h2>Edit</h2>
<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()) {
#Html.ValidationSummary(true)
<fieldset>
<legend>Parcel</legend>
#Html.HiddenFor(model => model.parcel.id)
<div class="editor-label">
#Html.LabelFor(model => model.parcel.Forename)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.parcel.Forename)
#Html.ValidationMessageFor(model => model.parcel.Forename)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.parcel.Surname)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.parcel.Surname)
#Html.ValidationMessageFor(model => model.parcel.Surname)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.parcel.CompanyName)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.parcel.CompanyName)
#Html.ValidationMessageFor(model => model.parcel.CompanyName)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.parcel.Address1)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.parcel.Address1)
#Html.ValidationMessageFor(model => model.parcel.Address1)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.parcel.Address2)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.parcel.Address2)
#Html.ValidationMessageFor(model => model.parcel.Address2)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.parcel.Address3)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.parcel.Address3)
#Html.ValidationMessageFor(model => model.parcel.Address3)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.parcel.Postcode)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.parcel.Postcode)
#Html.ValidationMessageFor(model => model.parcel.Postcode)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.ParcelStatus)
</div>
<div class="editor-field">
#Html.DropDownListFor(model => model.parcel.TrackingStatus, Model.TrackStatus)
#Html.ValidationMessageFor(model => model.ParcelStatus)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.parcel.TrackingNumber)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.parcel.TrackingNumber)
#Html.ValidationMessageFor(model => model.parcel.TrackingNumber)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.parcel.CustomerId)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.parcel.CustomerId)
#Html.ValidationMessageFor(model => model.parcel.CustomerId)
</div>
<p>
<input type="submit" value="Save" />
</p>
</fieldset>
}
<div>
#Html.ActionLink("Back to List", "Index")
You need to populate all of your view model's properties; not just the ID. The ParcelEditViewModel has no knowledge of what's in your database.
public ActionResult Edit(int id)
{
Parcel parcel = _parcelDao.GetParcel(id);
ParcelEditViewModel viewModel = new ParcelEditViewModel();
viewModel.id = parcel.id;
// Populate other properties! These may not be right.
viewModel.ProductName = parcel.Title;
viewModel.RecipientName; = parcel.RecipientName;
return View(viewModel);
}
There are mapping libraries such as AutoMapper that can help to streamline this.

How auto retrieve data from database in mvc?

It is a create view page where i have insert supplier information and it is inserting data successfully. i want to get this data automatically when i will enter a name and it exist it will show all of the data in these field, if not exist then i will save to the table.
#model FCBook.Supplier
#{
ViewBag.Title = "Create";
}
<h2>Create</h2>
#using (Html.BeginForm()) {
#Html.ValidationSummary(true)
<fieldset>
<legend>Supplier</legend>
<div class="editor-label">
#Html.LabelFor(model => model.SupplierName)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.SupplierName)
#Html.ValidationMessageFor(model => model.SupplierName)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Email)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Email)
#Html.ValidationMessageFor(model => model.Email)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.PhoneNo)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.PhoneNo)
#Html.ValidationMessageFor(model => model.PhoneNo)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Address)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Address)
#Html.ValidationMessageFor(model => model.Address)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Area)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Area)
#Html.ValidationMessageFor(model => model.Area)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.District)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.District)
#Html.ValidationMessageFor(model => model.District)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Division)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Division)
#Html.ValidationMessageFor(model => model.Division)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Country)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Country)
#Html.ValidationMessageFor(model => model.Country)
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
My controller action to this create view is
public ActionResult Create()
{
return View();
}
//
// POST: /Supplier/Create
[HttpPost]
public ActionResult Create(Supplier collection)
{
try
{
// TODO: Add insert logic here
var db = new PetaPoco.Database("FCBook");
if (collection != null)
{
collection.Insert();
}
return RedirectToAction("Index");
}
catch
{
return View();
}
}
I think you want to look into using Remote validation. It can be triggered after a user enters a value into one of your fields. I'm using this approach to populate other fields upon such an event occurring.

MVC4 validation is not working even i used required

i have this class in the model
public class Tenant :User
{
[Required]
public string PassportNumber { get; set; }
[Required]
public string image { get; set; }
[Required]
public string passportImage { get; set; }
}
in the view i have this code :
#using (Html.BeginForm("RegisterTenant", "Tenant", FormMethod.Post,
new { enctype = "multipart/form-data" })){
<div class="editor-label">
#Html.LabelFor(model => model.FirstName)
</div>
<div class="editor-field">
#Html.TextBoxFor(x => x.FirstName, new {placeholder = "Enter Your First Name" })
#Html.ValidationMessageFor(model => model.FirstName)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.LastName)
</div>
<div class="editor-field">
#Html.TextBoxFor(model => model.LastName, new { placeholder = "Enter Your Last Name"})
#Html.ValidationMessageFor(model => model.LastName)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Password)
</div>
<div class="editor-field">
#Html.TextBoxFor(model => model.Password, new { placeholder = "Enter Your Password"})
#Html.ValidationMessageFor(model => model.Password)
</div>
<div class="editor-field">
<label>Password Again</label>
<input type="text" placeholder="Enter your password again" name="Password2"/>
<span class="errorMessage"></span>
</div>
<div class="editor-label">
#Html.LabelFor(model => model.MobileNumber)
</div>
<div class="editor-field">
#Html.TextBoxFor(model => model.MobileNumber, new { placeholder = "Enter Your Mobile Number"})
#Html.ValidationMessageFor(model => model.MobileNumber)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.PassportNumber)
</div>
<div class="editor-field">
#Html.TextBoxFor(model => model.PassportNumber, new {placeholder = "Enter Your Passport Number"})
#Html.ValidationMessageFor(model => model.PassportNumber)
</div>
<div class="editor-field">
<label for="file">Upload You Passport:</label>
<input type="file" name="file" id="passport" style="width: 100%;" />
<span class="errorMessage"></span>
</div>
<div class="editor-field">
<label for="file">Upload You Image:</label>
<input type="file" name="file" id="image" style="width: 100%;" />
<span class="errorMessage"></span>
</div>
<input type="submit" value="Register" class="submit"/>
}
my question
even though i used validation message and the required tag, when i press the submit button, it works though the fields are empty.
what am i doing wrong?
When you are going to use JQuery validation in a view, you have to include the required JQuery validation files in the view.
#section scripts {
#Scripts.Render("~/bundles/jqueryval")
}

ASP MVC3 how to add system current date?

I have form like
#using (Html.BeginForm()) {
#Html.ValidationSummary(true)
<fieldset>
<legend>Course</legend>
#Html.HiddenFor(model => model.CId)
<div class="editor-label">
#Html.LabelFor(model => model.CName)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.CName)
#Html.ValidationMessageFor(model => model.CName)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Cteator)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Cteator)
#Html.ValidationMessageFor(model => model.Cteator)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.date)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.date)
#Html.ValidationMessageFor(model => model.date)
</div>
<p>
<input type="submit" value="Save" />
</p>
</fieldset>
}
I want to insert system current date and time in the field of Date field. How can i do this. Model and cotroller are already create by scaffolding.
Insert this before you call the editor (assuming your property is a DateTime)
#{ Model.date = DateTime.Now; }
If your property is a string, call DateTime.Now.ToString().
You could set the default value in the corresponding controller action:
public ActionResult Index() {
return View(new SomeModel { date = DateTime.Now });
}
Change your code as mention below
#{ Model.date = DateTime.Now.ToString(); }
#Html.ValidationSummary(true)
<fieldset>
<legend>Course</legend>
#Html.HiddenFor(model => model.CId)
<div class="editor-label">
#Html.LabelFor(model => model.CName)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.CName)
#Html.ValidationMessageFor(model => model.CName)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Cteator)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Cteator)
#Html.ValidationMessageFor(model => model.Cteator)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.date)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.date)
#Html.ValidationMessageFor(model => model.date)
</div>
<p>
<input type="submit" value="Save" />
</p>
</fieldset>

Resources