HiddenInput not working while render on view MVC 5 - asp.net-mvc

I have used HiddenInput(DisplayValue = false) like:
[HiddenInput(DisplayValue = false)]
[DisplayName("Updated By")]
public string Updatedby { get; set; }
but it's still rendering as EditorFor
<div class="form-group">
#Html.LabelFor(model => model.Updatedby, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Updatedby, new { htmlAttributes = new { #class = "form-control" } }) #Html.ValidationMessageFor(model => model.Updatedby, "", new { #class = "text-danger" })
</div>
</div>
I want to render it as hidden field. How can I do that? Thank you.

You can use
#Html.HiddenFor(m=>m.Updatedbynew ,new { #class = "form-control" })
for rendering a hidden model-binded field in DOM.

Related

Why when Check if the user already exists in ASP.NET MVC database first not working?

I checked more than one post in this site and tried more than one solution but still I cannot check the user exist or not when register new user , I tried the following code :
[HttpPost]
public ActionResult register(Registration reg)
{
if (ModelState.IsValid)
{
var userexist = db.Registration.Any(x => x.username == reg.username);
if (userexist)
{
ModelState.AddModelError("username", "User with this name already exists");
return View(reg);
}
else
{
db.Registration.Add(reg);
db.SaveChanges();
return RedirectToAction("Index");
}
}
return View();
}
this is registration model :
namespace registration.Models
{
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
public partial class Registration
{
public int Userid { get; set; }
[Required]
[Display(Name ="ID or Iqama No ")]
public string username { get; set; }
[Required]
[Display(Name = "Medical Record Number ")]
public int PatientNo { get; set; }
[Required]
[Display(Name = "Mobile ")]
public string Mobile { get; set; }
[Display(Name = "Email Address ")]
[DataType(DataType.EmailAddress)]
public string Email { get; set; }
[Required]
[DataType(DataType.Password)]
public string Password { get; set; }
}
this is the view code and submit button there create button:
#model registration.Models.Registration
#{
ViewBag.Title = "Register New User";
}
<h2>register</h2>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Registration Window</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.username, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10" >
#Html.EditorFor(model => model.username, new { htmlAttributes = new { #type = "number", #min = "0", #value = "0", #class = "form-control" } })
#Html.ValidationMessageFor(model => model.username, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.PatientNo, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.PatientNo, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.PatientNo, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Mobile, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Mobile, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Mobile, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Email, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Email, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Email, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Password, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Password, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Password, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
}
<div>
#Html.ActionLink("Back to List", "Login")
</div>
what is the missing in my code why its not working when click enter or tab or by mouse click its not checking ?
Your code correct and no errors ,
You said
"when click enter or tab or by mouse click its not checking ?"
This code will work when you click the button Submit or Create .
The code will validate the username exist or not and not when you navigate grom the username field.
Try this:
#using (Html.BeginForm("register", "YourControllerName", FormMethod.Post, new { #id = "LoginForm", #autocomplete = "off"}))
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Registration Window</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.username, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10" >
#Html.EditorFor(model => model.username, new { htmlAttributes = new { #type = "number", #min = "0", #value = "0", #class = "form-control" } })
#Html.ValidationMessageFor(model => model.username, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.PatientNo, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.PatientNo, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.PatientNo, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Mobile, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Mobile, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Mobile, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Email, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Email, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Email, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Password, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Password, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Password, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
}
Controller:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult register(Registration reg)
{
if (ModelState.IsValid)
{
var userexist = db.Registration.Any(x => x.username == reg.username);
if (userexist)
{
ModelState.AddModelError("username", "User with this name already exists");
return View(reg);
}
else
{
db.Registration.Add(reg);
db.SaveChanges();
return RedirectToAction("Index");
}
}
return View();
}

The model item passed into the dictionary is of type 'System.Collections.Generic.List but this dictionary requires a model item of type 'XXX.XXX.XXX'

I am trying to use strongly typed dropdownlist for my application. I have textbox fields as well. But when i pass #model Aayumitra.Models.RegisterViewModel
#using Aayumitra.Models; I am getting below error.
The model item passed into the dictionary is of type 'System.Collections.Generic.List`1[System.Web.Mvc.SelectListItem]', but this dictionary requires a model item of type 'XXX.XXX.XXX'.
AccountViewModel
public class RegisterViewModel
{
public string FirstName { get; set; }
public string MiddleName { get; set; }
public string LastName { get; set; }
public string Gender { get; set; }
public IEnumerable<SelectListItem> Genders { get; set; }
}
Controller
private static List<SelectListItem> GetGenders()
{
AayumitraDBEntities db = new AayumitraDBEntities();
List<SelectListItem> GenderList = (from p in db.Genders.AsEnumerable()
select new SelectListItem
{
Text = p.GenderType,
Value = p.GenderId.ToString()
}).ToList();
//Add Default Item at First Position.
GenderList.Insert(0, new SelectListItem { Text = "--Select Gender--", Value = "" });
return GenderList;
}
//
// GET: /Account/UpdatePatient
[AllowAnonymous]
public ActionResult UpdatePatient()
{
List<SelectListItem> GenderList = GetGenders();
return View(GenderList);
}
View
#model Aayumitra.Models.RegisterViewModel
#using Aayumitra.Models;
#using (Html.BeginForm())
{
<div class="row">
<div class="col-md-4">
<div class="profile-container">
<div class="profile">
<img src="~/Content/images/logo.png" width="100" />
</div>
<div class="profile-info">
<p>
#Html.TextBox("FullName", User.Identity.Name.ToString(), new { #readonly = "readonly", #disabled = "disabled" })
</p>
</div>
</div>
</div>
</div>
<div class="dropdown-divider"></div>
<div class="row">
<div class="col-sm-3">
<div class="form-group">
#Html.LabelFor(model => model.FirstName, htmlAttributes: new { #class = "control-label col-md-2" })
#Html.EditorFor(model => model.FirstName, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.FirstName, "", new { #class = "text-danger" })
</div>
</div>
<div class="col-sm-3">
<div class="form-group">
#Html.LabelFor(model => model.MiddleName, htmlAttributes: new { #class = "control-label col-md-2" })
#Html.EditorFor(model => model.MiddleName, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.MiddleName, "", new { #class = "text-danger" })
</div>
</div>
<div class="col-sm-3">
<div class="form-group">
#Html.LabelFor(model => model.LastName, htmlAttributes: new { #class = "control-label col-md-2" })
#Html.EditorFor(model => model.LastName, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.LastName, "", new { #class = "text-danger" })
</div>
</div>
<div class="col-sm-3">
<div class="form-group">
#Html.LabelFor(model => model.Gender, htmlAttributes: new { #class = "control-label col-md-2" })
#Html.DropDownListFor(x => Model.Gender, new SelectList(Model.Genders, "Value", "Text"), htmlAttributes: new { #class = "form-control", id = "Gender" })
</div>
</div>
</div>
}
if your View is supposed to be for UpdatePatient, then you want to create a model of type RegisterViewModel and add Genders to it, and then pass that model to the View, like this:
public ActionResult UpdatePatient()
{
List<SelectListItem> GenderList = GetGenders();
return View(new RegisterViewModel
{
FirstName = "",
MiddleName = "middle",
LastName = "last",
Genres = GenderList
});
}

POST form in MVC - No Values being written to DB

I have a model that I'm trying to edit with a form:
public class Basiclife
{
[Key]
public int Id { get; set; }
public int? ResponseId { get; set; }
public string Plantype { get; set; }
public int Enrolledftes { get; set; }
public decimal Pctemployer { get; set; }
public decimal Fixedbenamt { get; set; }
public decimal Salarymult { get; set; }
public decimal Bencap { get; set; }
}
And a view wrapper to edit it (with the editor in a separate partial view):
<h2>CreateBasicLifeResponse</h2>
<div id="planList">
#using (Html.BeginForm("CreateBasicLifeResponse", "Surveys"))
{
<div id="editorRows">
#foreach (var item in Model.basiclives)
{
#Html.Partial("_BasicLifeResponse", item)
}
</div>
#Html.ActionLink("Add", "BasicLifeResponse", null, new { id = "addItem", #class = "button" });
<input type="submit" value="submit" />
}
</div>
The wrapper's model is:
public class ResponseBasicLife
{
public Response response { get; set; }
public List<Basiclife> basiclives { get; set; }
}
Here's the partial view:
#using CustomSurveyTool.Models
#model Basiclife
<div class="editorRow">
#using (Html.BeginCollectionItem("basiclives"))
{
<div class="form-horizontal">
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.Plantype, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Plantype, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Plantype, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Enrolledftes, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Enrolledftes, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Enrolledftes, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Pctemployer, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Pctemployer, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Pctemployer, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Fixedbenamt, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Fixedbenamt, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Fixedbenamt, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Salarymult, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Salarymult, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Salarymult, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Bencap, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Bencap, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Bencap, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
X
</div>
</div>
}
</div>
Here's my controller action where I'm getting the proper responseId and assigning it to the form values:
public ActionResult CreateBasicLifeResponse(ResponseBasicLife model)
{
for (var i = 1; i < model.basiclives.Count; i++)
{
string currentUserId = User.Identity.GetUserId();
Response targetresponse = db.response.FirstOrDefault(x => x.Userid == currentUserId);
int responseid = targetresponse.Id;
model.basiclives[i].ResponseId = responseid;
db.basiclife.Add(model.basiclives[i]);
db.SaveChanges();
}
ResponseBasicLife basicliferesponse = new ResponseBasicLife
{
basiclives = new List<Basiclife>
{
new Basiclife { }
}
};
return View(basicliferesponse);
}
The only thing that's being written to the database is the ResponseID. How do I get the rest of the values to write to it?
This is a unique case where EditorFor could help. Essentially an object will have its editor template which is kind of like a partial view but specific to editing forms.
Secondly, the being form you are specifying is expecting the model of the view that you specified - in your case the viewWrapper. If for instance you specified a List<BasicLife>, then that is what the postBack shall be expecting, and not the BasicLife object. Below is how your postback would look like.
[HttpPost]
public ActionResult CreateBasicLifeResponse(List<BasicLife> model){
//your code goes here
}
From your view though, it looks clear that Model contains more than just a list. That is what shall be expected from the callback.

Passing ViewModel List Data to controller

I have a ViewModel as such:
public class AddNewsModel
{
public List<CategoriesModel> Category { get; set; }
public NewsModel NewsModel { get; set; }
}
where Category contains:
public class CategoriesModel
{
public string Name { get; set; }
public int ID { get; set; }
}
and NewsModel contains:
public class NewsModel
{
public int ID { get; set; }
public string Category { get; set; }
public String Headline { get; set; }
public string Source { get; set; }
public DateTime Publish_Date { get; set; }
public string Text { get; set; }
public string Summary { get; set; }
public string TimeAgo { get; set; }
public string ImageURL { get; set; }
public string CategoryID { get; set; }
}
I have a View where I take form input for News using NewsModel, but I want to display possible categories as a dropdown list or select Tag from the CategoriesModel.
This is My View:
<h2>Add a News Article</h2>
#if (TempData["Success"] != null)
{
<p class="alert alert-success" id="successMessage">#TempData["Success"]</p>
}
#using (Html.BeginForm("AddNews", "Admin", FormMethod.Post))
{
#Html.AntiForgeryToken()
<div class="form-horizontal" id="addNews">
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.Label("News ID", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-1">
#Html.EditorFor(model => model.NewsModel.ID, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.NewsModel.ID, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.NewsModel.Category, htmlAttributes: new { #class = "control-label col-md-2" })
#Html.DropDownListFor(model => model.Category, new SelectList(Model.Category), "Select Category")
#*<div class="col-md-2">
<select form="addNews" id="NewsModel_Category" name="NewsModel.Category">
#foreach (var item in Model.Category)
{
<option value="#item.Name">#item.Name</option>
}
</select>
</div>*#
</div>
<div class="form-group">
#Html.LabelFor(model => model.NewsModel.Headline, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-6">
#Html.EditorFor(model => model.NewsModel.Headline, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.NewsModel.Headline, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.NewsModel.Source, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-6">
#Html.EditorFor(model => model.NewsModel.Source, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.NewsModel.Source, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.Label("Publish Date", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-4">
#Html.EditorFor(model => model.NewsModel.Publish_Date, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.NewsModel.Publish_Date, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.NewsModel.Text, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-6">
#Html.TextAreaFor(model => model.NewsModel.Text, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.NewsModel.Text, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.NewsModel.Summary, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-6">
#Html.TextAreaFor(model => model.NewsModel.Summary, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.NewsModel.Summary, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.NewsModel.ImageURL, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-6">
#Html.EditorFor(model => model.NewsModel.ImageURL, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.NewsModel.ImageURL, "", 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 line of code:
#Html.DropDownListFor(model => model.Category, new SelectList(Model.Category), "Select Category")
gets all the categories, but only displays them as the model I have imported int the view, viz. "MVCApplication.Models.AddNewsModel", instead of a category like "World" or "Tech"
This code that I have commented, returns null when i try to get the data in my HTTPPost controller action using formcollection. I have tried using the ID that i have provided as: string x= formCollection["category"];
<div class="col-md-2">
<select form="addNews" id="category" name="category">
#foreach (var item in Model.Category)
{
<option value="#item.Name">#item.Name</option>
}
</select>
</div>
How can I show the categories in my View, as well as get the value in the controller?
Any help would be appreciated.
Edit:
I am populating The Categories list in my controller action as:
public ActionResult AddNews()
{
AddNewsModel AddNewsModel = new AddNewsModel();
AddNewsModel.Categories = new NewsArticles().GetCategories();
return View(AddNewsModel);
}
Changing my model to an Ienumerable instead of list causes errors in my controller I cannot seem to solve.
your model should be like this:
public class AddNewsModel
{
public IEnumerable<SelectListItem> CategorySelectList { get; set; }
public int CategoryId {get; set;}
public NewsModel NewsModel { get; set; }
}
and in the view :
#Html.DropDownListFor(model => model.CategoryId, Model.CategorySelectList, "Select Category")
for more details -> link
You should have both Cateogory and List with all categories in the model
public class AddNewsModel
{
public int Category { get; set; }
public IEnumerable<SelectListItem> Categories { get; set;}
public NewsModel NewsModel { get; set; }
}
View
update your dropdownlist with list.
<h2>Add a News Article</h2>
#if (TempData["Success"] != null)
{
<p class="alert alert-success" id="successMessage">#TempData["Success"]</p>
}
#using (Html.BeginForm("AddNews", "Admin", FormMethod.Post))
{
#Html.AntiForgeryToken()
<div class="form-horizontal" id="addNews">
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.Label("News ID", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-1">
#Html.EditorFor(model => model.NewsModel.ID, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.NewsModel.ID, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.NewsModel.Category, htmlAttributes: new { #class = "control-label col-md-2" })
#Html.DropDownListFor(model => model.Category, Model.Categories, "Select Category")
#*<div class="col-md-2">
<select form="addNews" id="NewsModel_Category" name="NewsModel.Category">
#foreach (var item in Model.Category)
{
<option value="#item.Name">#item.Name</option>
}
</select>
</div>*#
</div>
<div class="form-group">
#Html.LabelFor(model => model.NewsModel.Headline, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-6">
#Html.EditorFor(model => model.NewsModel.Headline, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.NewsModel.Headline, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.NewsModel.Source, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-6">
#Html.EditorFor(model => model.NewsModel.Source, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.NewsModel.Source, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.Label("Publish Date", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-4">
#Html.EditorFor(model => model.NewsModel.Publish_Date, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.NewsModel.Publish_Date, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.NewsModel.Text, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-6">
#Html.TextAreaFor(model => model.NewsModel.Text, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.NewsModel.Text, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.NewsModel.Summary, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-6">
#Html.TextAreaFor(model => model.NewsModel.Summary, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.NewsModel.Summary, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.NewsModel.ImageURL, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-6">
#Html.EditorFor(model => model.NewsModel.ImageURL, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.NewsModel.ImageURL, "", 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>
}

Getting vailidation anomalies in MVC

I'm following this (https://learn.microsoft.com/en-us/aspnet/mvc/overview/older-versions-1/getting-started-with-mvc/getting-started-with-mvc-part7), but I am seeing some strange things I when I view the webpage.
1) The ReleaseDate says its a required filed (even though its not marked as such in the code) , and I cannot see why its doing this.
and
2) the Price "works" if the values is 100.50, or less . if its 100.51 or higher, then the message kicks in. My understanding is that the message should kick in # 100.01... or am I wrong ?
namespace Movies.Models
{
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
public partial class Movie
{
public int Id { get; set; }
[Required(ErrorMessage = "Titles are required")]
public string Title { get; set; }
public System.DateTime ReleaseDate { get; set; }
public string Genre { get; set; }
[Required(ErrorMessage = "The Price is required.")]
[Range(5, 100, ErrorMessage = "Movies cost between £5 and £100.")]
public decimal Price { get; set; }
}
}
Could someone point out what I'm doing wrong ?
thanks
view code is
#model Movies.Models.Movie
#{
ViewBag.Title = "Create";
}
<h2>Create</h2>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Movie</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.Title, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Title, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Title, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.ReleaseDate, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.ReleaseDate, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.ReleaseDate, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Genre, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Genre, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Genre, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Price, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Price, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Price, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
First question.
Make your DateTime nullable like this:
public System.DateTime? ReleaseDate { get; set; }
Second question:
Specify Range number type to double with literal d like this:
[Range(5d, 100d, ErrorMessage = "Movies cost between £5 and £100.")]
public decimal Price { get; set; }

Resources