I have the following in my view:
<fieldset>
<legend>User Registration</legend>
<div class="editor-label">
#Html.LabelFor(m => m.UsrName)
</div>
<div class="editor-field">
#Html.TextBoxFor(m => m.UsrName)
#Html.ValidationMessageFor(m => m.UsrName)
</div>
<div class="editor-label">
#Html.LabelFor(m => m.Pwd)
</div>
<div class="editor-field">
#Html.PasswordFor(m => m.Pwd)
#Html.ValidationMessageFor(m => m.Pwd)
</div>
<div class="editor-label">
#Html.LabelFor(m => m.ReEnterPwd)
</div>
<div class="editor-field">
#Html.PasswordFor(m => m.ReEnterPwd)
#Html.ValidationMessageFor(m => m.ReEnterPwd)
</div>
<fieldset>
<legend>Location</legend>
<span id="locationDiv">
#Html.RadioButtonFor(m => m.Location, "Loc1") #Html.Label("Loc1")
</span>
#Html.RadioButtonFor(m => m.Location, "Loc2") #Html.Label("Loc2")
#Html.ValidationMessageFor(m => m.Location)
</fieldset>
<fieldset>
<legend>Role</legend>
#Html.RadioButtonFor(m => m.Role, "User") #Html.Label("User")
#Html.RadioButtonFor(m => m.Role, "Admin") #Html.Label("Admin")
#Html.ValidationMessageFor(m => m.Role)
</fieldset>
<p>
<input type="submit" value="Register User" />
</p>
</fieldset>
Even if I don't have all the fields filled, it still goes to the controller even though they are all required. I thought
#Html.ValidationMessageFor
was supposed to prevent that.
[Required]
public string Location { get; set; }
[Required]
public string Role { get; set; }
[Required]
[Display(Name = "User Name")]
public string UsrName { get; set; }
[Required]
[StringLength(50, MinimumLength = 5, ErrorMessage = "Must have a minimum length of 5.")]
public string Pwd { get; set; }
[Required]
[Display(Name = "Re-enter Password")]
[StringLength(50, MinimumLength = 5, ErrorMessage = "Must have a minimum length of 5.")]
[Compare("Pwd", ErrorMessage = "The password and re-entered password do not match.")]
public string ReEnterPwd { get; set; }
You must include the following scripts in the view:
<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>
I had to include the JQuery Validation bundle at the bottom of my view in the scripts section.
I noticed this exists in all the baked in views for login and authentication but needs to be manually added to your custom views.
Example
#section scripts{
#Scripts.Render("~/bundles/jqueryval")
}
Related
been making a database to store users details when they register and have a login/logout page. All was going dandy until when the database updates in the 'UserController' and I get this error:
> 'Mvcflight.RegistrationEntities' does not contain a definition for
> 'User' and no extension method 'User' accepting a first argument of
> type 'Mvcflight.RegistrationEntities' could be found (are you missing
> a using directive or an assembly reference?)
Of course nothing happens on the actual website and nothing saves to the database.
public ActionResult Register(User U)
{
using (RegistrationEntities dc = new RegistrationEntities())
if (ModelState.IsValid)
{
//you should check duplicate registration here
dc.User.Add(U);
dc.SaveChanges();
ModelState.Clear();
U = null;
ViewBag.Message = "Successfully Registration Done";
}
return View(U);
}
The database can't update I don't know why, any ideas?
Here's my class:
public class User
{
public int Id { get; set; }
[Required(ErrorMessage = "Please provide username", AllowEmptyStrings = false)]
public string userName { get; set; }
[Required(ErrorMessage = "Please provide Password", AllowEmptyStrings = false)]
[DataType(System.ComponentModel.DataAnnotations.DataType.Password)]
[StringLength(50, MinimumLength = 8, ErrorMessage = "Password must be 8 char long.")]
public string userPassword { get; set; }
[Compare("Password", ErrorMessage = "Confirm password dose not match.")]
[DataType(System.ComponentModel.DataAnnotations.DataType.Password)]
public string ConfirmPassword { get; set; }
[Required(ErrorMessage = "Please provide full name", AllowEmptyStrings = false)]
public string fullName { get; set; }
[RegularExpression(#"^([0-9a-zA-Z]([\+\-_\.][0-9a-zA-Z]+)*)+#(([0-9a-zA-Z][-\w]*[0-9a-zA-Z]*\.)+[a-zA-Z0-9]{2,3})$",
ErrorMessage = "Please provide valid email id")]
public string userEmail { get; set; }
}
And my HTML code:
<h2>Register</h2>
#model Mvcflight.Models.User
#using (Html.BeginForm())
{
#Html.ValidationSummary(true)
<fieldset>
<legend>User</legend>
#Html.AntiForgeryToken()
#if (ViewBag.Message != null)
{
<div style="border:solid 1px green">
#ViewBag.Message
</div>
}
<div class="editor-label">
#Html.LabelFor(model => model.userName)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.userName)
#Html.ValidationMessageFor(model => model.userName)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.userEmail)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.userEmail)
#Html.ValidationMessageFor(model => model.userEmail)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.userPassword)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.userPassword)
#Html.ValidationMessageFor(model => model.userPassword)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.fullName)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.fullName)
#Html.ValidationMessageFor(model => model.fullName)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Id)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Id)
#Html.ValidationMessageFor(model => model.Id)
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
To note I have another database on the website, both sharing my 'FlightClass'
Thanks for any and all help, let me know if you need more info/code!!
:)
I have a form and using Grid.MVC to display in same page. When I try run my program, it show error : 'Model' conflicts with the declaration 'System.Web.Mvc.WebViewPage.Model'..
Here the sample of my code
This is my model
public class Course
{
[DisplayName("Customer Name")]
public string customer { get; set; }
[DisplayName("Contact")]
public string contact { get; set; }
[UIHint("DropDownList")]
[Required(ErrorMessage = "Please select the package")]
public int CoursePackageID { get; set; }
[Required]
public int CustomerID { get; set; }
[Required(ErrorMessage = "The date is required")]
[DisplayName("Date Of Register")]
public DateTime dtRegister { get; set; }
[DisplayName("Payment")]
public string payment { get; set; }
public List<CourseObject> lCourse { get; set; }
public class CourseObject
{
public int courseId { get; set; }
[DisplayName("Package")]
public string package { get; set; }
[DisplayName("Date Of Register")]
public DateTime date_register { get; set; }
[DisplayName("Payment")]
public string payment { get; set; }
}
}
And this is my CSHTML (Razor)
#model BangiProject.Models.Course
#using GridMvc.Html
#{
ViewBag.Title = "Register";
}
<h2>
Register</h2>
#using (Html.BeginForm())
{
#Html.ValidationSummary(true)
<fieldset>
<legend>Course</legend>
<div class="control-label">
#Html.LabelFor(model => model.customer)
</div>
<div class="form-control-static">
#Html.DisplayFor(model => model.customer)
</div>
<div class="control-label">
#Html.LabelFor(model => model.contact)
</div>
<div class="form-control-static">
#Html.DisplayFor(model => model.contact)
</div>
<div class="editor-label">
Category :
</div>
<div class="editor-field">
#Html.DropDownListFor(Model => Model.CoursePackageID, new SelectList(ViewBag.CoursePackage as System.Collections.IEnumerable, "id", "course_name", new { #style = "drop-down" }),
"-Choose Package-", new { id = "cat" })
</div>
<div class="editor-label">
#Html.LabelFor(model => model.dtRegister)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.dtRegister)
#Html.ValidationMessageFor(model => model.dtRegister)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.payment)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.payment)
#Html.ValidationMessageFor(model => model.payment)
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
<div class="row">
#Html.Grid(Model.lCourse).Columns(columns =>
{
columns.Add(c => c.courseId).Titled("ID")
.Sanitized(false)
.Encoded(false)
.RenderValueAs(o => Html.ActionLink("Edit", "Edit", "Merchant", new { id = o.courseId }, null).ToHtmlString());
columns.Add(c => c.package).Titled("Package").Filterable(true);
columns.Add(c => c.date_register).Titled("Date Of Register").Filterable(true);
}).WithPaging(25).Sortable(true)
</div>
<div>
#Html.ActionLink("Back to List", "Index")
</div>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
The error show on this line
#Html.Grid(Model.lCourse).Columns
Please advice...
Usually this means that you're using the reserved "Model" keyword erroneously somewhere. In your case:
#Html.DropDownListFor(Model => Model.CoursePackageID...
Change this to:
#Html.DropDownListFor(model => model.CoursePackageID...
Try changing the line in question as below(lowercase 'm')...
#Html.Grid(model.lCourse).Columns
This is my Create.cshtml file
#model Bartering.Models.Advertisement
#{
ViewBag.Title = "Create";
}
<h2>Create</h2>
<script src="#Url.Content("~/Scripts/jquery-1.7.1.js")" type="text/javascript"></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/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("Create", "Advertisement", FormMethod.Post, new { enctype="multipart/form-data" })) {
#Html.ValidationSummary(true)
<fieldset>
<legend>TASK</legend>
<div class="editor-label">
#Html.LabelFor(model => model.Task_For)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Task_For)
#Html.ValidationMessageFor(model => model.Task_For)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.UserName)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.UserName)
#Html.ValidationMessageFor(model => model.UserName)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Department)
</div>
<div class="editor-field">
#Html.DropDownListFor(model => model.Department,(SelectList)ViewBag.CategoryList)
#Html.ValidationMessageFor(model => model.Department)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Attachment)
</div>
<div class="editor-field">
<input type="file" id="MyFile" runat="server" />
#Html.ValidationMessageFor(model => model.Attachment)
</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.Date)
</div>
#inherits System.Web.Mvc.WebViewPage<System.DateTime?>
#Html.TextBox("", (Model.HasValue ? Model.Value.ToString("MM/dd/yyyy") : DateTime.Today.ToShortDateString()), new { #class = "datefield" })
<div class="editor-field">
#Html.EditorFor(model => model.Date)
#Html.ValidationMessageFor(model => model.Date)
</div>
<p>
<input type="submit" value="Post" />
</p>
</fieldset>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
this is my Advertisement model class
using System;
using System.Drawing; // Image type is in this namespace
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.ComponentModel;
namespace Bartering.Models
{
public class Advertisement
{
[Key]
public int ID { get; set; }
[Required]
[StringLength(100)]
public string Task_For { get; set; }
public Guid OwnerID { get; set; }
public string UserName { get; set; }
[Required]
public string Department { get; set; }
public byte[] Attachment { get; set; }
[Required]
[StringLength(200)]
public string Description { get; set; }
public int Count { get; set; }
[DisplayName("Date")]
[DataType(DataType.DateTime,ErrorMessage="Date non valid")]
[DisplayFormat(DataFormatString="{0:MM/dd/yy}",ApplyFormatInEditMode=true)]
[Required]
public DateTime Date { get; set; }
}
}
when I run my application it gives the following error
The 'inherits' keyword is not allowed when a 'model' keyword is used.
Line 66: #inherits System.Web.Mvc.WebViewPage<System.DateTime?>
I want to add a date picker to add the date.how do I fix this please help me to fix this.
In your view you have
#inherits System.Web.Mvc.WebViewPage<System.DateTime?>
#Html.TextBox("", (Model.HasValue ? Model.Value.ToString("MM/dd/yyyy") :
Just remove inherits line "#inherits System.Web.Mvc.WebViewPage "
UPDATE after comment
Please read about inherits http://odetocode.com/blogs/scott/archive/2011/01/13/razor-tip-2-inheritance-amp-configuration.aspx
Simply talkin inherits let know razor of which time would be your #Model property.
To make date picker work you have #Html.EditorFor(model => model.Date) and it will render (Html5 date picker) it will work in modern browsers.
To make you second example working please follow format
#Html.TextBox("name", "value", new {type="date"})
I am working on mvc - 3. I have created a register model and a register view.
Register view :
#using (Html.BeginForm())
{
#Html.ValidationSummary(true, "Correct the errors and try again.")
<div>
<fieldset>
<legend>Account Information</legend>
<div class="editor-label">
#Html.LabelFor(m => m.UserName)
</div>
<div class="editor-field">
#Html.TextBoxFor(m => m.UserName)
#Html.ValidationMessageFor(m => m.UserName)
</div>
<div class="editor-label">
#Html.LabelFor(m => m.Email)
</div>
<div class="editor-field">
#Html.TextBoxFor(m => m.Email)
#Html.ValidationMessageFor(m => m.Email)
</div>
<div class="editor-label">
#Html.LabelFor(m => m.Password)
</div>
<div class="editor-field">
#Html.PasswordFor(m => m.Password)
#Html.ValidationMessageFor(m => m.Password)
</div>
<div class="editor-label">
#Html.LabelFor(m => m.ConfirmPassword)
</div>
<div class="editor-field">
#Html.PasswordFor(m => m.ConfirmPassword)
#Html.ValidationMessageFor(m => m.ConfirmPassword)
</div>
<div class="editor-label">
#Html.LabelFor(m => m.Question)
</div>
<div class="editor-field">
#Html.DropDownListFor(m => m.Question, new SelectList(Model.Questions))
#Html.HiddenFor(m => m.Questions)
</div>
<div class="editor-label">
#Html.LabelFor(m => m.Answer)
</div>
<div class="editor-field">
#Html.TextBoxFor(m => m.Answer)
#Html.ValidationMessageFor(m => m.Answer)
</div>
<p>
<input type="submit" value="Register" />
</p>
</fieldset>
</div>
}
Register Model
public class RegisterModel
{
[Required]
[Display(Name = "User name")]
public string UserName { get; set; }
[Required]
[RegularExpression(#"^[a-z0-9_\+-]+(\.[a-z0-9_\+-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*\.([a-z]{2,4})$", ErrorMessage="Invalid email address")]
[DataType(DataType.EmailAddress)]
[Display(Name = "Email address")]
public string Email { get; set; }
[Required]
[StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
[DataType(DataType.Password)]
[Display(Name = "Password")]
public string Password { get; set; }
[DataType(DataType.Password)]
[Display(Name = "Confirm password")]
[Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
public string ConfirmPassword { get; set; }
[Display(Name = "Security question")]
public string Question { get; set; }
[Display(Name = "Security question")]
public List<string> Questions { get; set; }
[Display(Name = "Security answer")]
public string Answer { get; set; }
}
My issue is when we submit the register form to server than all data will send to server except questions list. So if validation fails than i am getting the exception Model.Questions is null. How can i solve this issue ?
Look at my example and you will understand how it works:
#{
List<string> test = new List<string> { "111", "222", "333" };
}
<div id="test1">
#Html.HiddenFor(x => test)
</div>
<div id="test2">
#for (int i = 0; i < test.Count; i++)
{
#Html.HiddenFor(x => test[i])
}
</div>
Will render:
<div id="test1">
<input id="test" name="test" type="hidden" value="System.Collections.Generic.List`1[System.String]" />
</div>
<div id="test2">
<input id="test_0_" name="test[0]" type="hidden" value="111" />
<input id="test_1_" name="test[1]" type="hidden" value="222" />
<input id="test_2_" name="test[2]" type="hidden" value="333" />
</div>
You need to either serialize the list to a hidden form field, or make sure you reload the list before your return View(model);
Try this
public ActionResult SomeAction(RegisterModel model)
{
if(ModelState.IsValid)
{
// perform the functionality when Mmodel is Valid
return View(model);
}
// bind data to Question list if model is fail
model.Questions = new List<String>();
return View(model);
}
NOTE: you need to bind the data to Question List when your model validation is fail before returning View.
I have the following view, which fails to validate on Title, and NewsContent. Title validation works but not NewsContent. How can i fix it.
#model Foo.NewsViewModel
#{
ViewBag.Title = "Create";
}
#using (Html.BeginForm("Create", "News", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<div>
<fieldset>
<legend>Category Information</legend>
<div class="editor-label">
#Html.LabelFor(m => m.News.Title)
</div>
<div class="editor-field">
#Html.TextBoxFor(m => m.News.Title)
#Html.ValidationMessageFor(m => m.News.Title)
</div>
<div class="editor-label">
#Html.LabelFor(m => m.News.NewsContent)
</div>
<div class="editor-field" id="container">
#Html.TextAreaFor(m => m.News.NewsContent)
#Html.ValidationMessageFor(m => m.News.NewsContent)
</div>
<div class="editor-label">
#Html.LabelFor(m => m.News.Thumbnail)
</div>
<div class="editor-field">
<input type="file" name="files" id="thumbnail" />
</div>
<div class="editor-label">
#Html.LabelFor(m => m.News.Image)
</div>
<div class="editor-field">
<input type="file" name="files" id="original" />
</div>
<div class="editor-label">
#Html.Label("SelectedCategoryId")
</div>
<div class="editor-field">
#Html.DropDownListFor(m => m.SelectedCategoryId, Model.Categories)
</div>
<div class="editor-label">
Publish
</div>
<div class="editor-field">
#Html.CheckBoxFor(m => m.News.Published, new { #checked = "checked" })
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
</div>
}
and here is the model|:
public class News : IStorable
{
[Required]
[Display(Name = "Title")]
public virtual string Title { get; set; }
[Required]
[Display(Name = "Content")]
public virtual string NewsContent { set; get; }
......
Issue: Title validation works but not NewsContent.
Validations is not work, because of using Html.TextAreaFor() helper to render the "NewsContent" property,
Here is the code to make it work:
Change your model as:
Decorate the 'NewsContent' property with [DataType] attribute and set the data type as 'MultilineText'. This will indicates that the editor for this property should be a multi-line text input.
public class News : IStorable
{
[Required]
[Display(Name = "Title")]
public virtual string Title { get; set; }
[Required()]
[Display(Name = "Content")]
[DataType(DataType.MultilineText)]
public virtual string NewsContent { set; get; }
//....
}
In the view use Html.EditorFor() helper instead of Html.TextAreaFor() for the 'News.NewsContent' property.
//....
<div class="editor-label">
#Html.LabelFor(m => m.News.NewsContent)
</div>
<div class="editor-field" id="container">
#*#Html.TextAreaFor(m => m.News.NewsContent)*#
#Html.EditorFor(m => m.News.NewsContent)
#Html.ValidationMessageFor(m => m.News.NewsContent)
</div>
//....