I have 2 two pages.
First page
#model IncidentsDB.UI.Web.ViewModels.Account.LogOnModel
#{
ViewBag.Title = "Вход в систему";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<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>
<div class="headerLabel">
<h3>Вход в систему</h3>
</div>
#using (Html.BeginForm("Register", "Account", FormMethod.Get, new { id = "searchForm" }))
{
<div class="createUserDiv">
<input type="submit" class="lightGreenGradientBtn" id="createUserBtn" value="Добавить нового пользователя" />
</div>
}
#using (Html.BeginForm()) {
<div class="loginDataDiv">
<div class="leftItemDiv labelDiv" style="padding-left: 45px">
#Html.LabelFor(m => m.UserName)
</div>
<div class="editor-field rightItemDiv">
#Html.TextBoxFor(m => m.UserName)
</div>
<div class="loginErrorDiv labelDiv">
#Html.ValidationMessageFor(m => m.UserName)
</div>
<div class="leftItemDiv labelDiv" style="padding-left: 45px">
#Html.LabelFor(m => m.Password)
</div>
<div class="editor-field rightItemDiv noWrap">
#Html.TextBoxFor(m => m.Password)
</div>
<div class="rememberPswdDivCollapse" id="rememberPswdDiv">
#Html.ActionLink("Вспомнить пароль", "RestorePassword","Account", new { #class = "rememberPswdLink" })
</div>
<div class="loginErrorDiv">
#Html.ValidationMessageFor(m => m.Password)
</div>
<div class="clearStyles rightItemDiv">
<input type="submit" class="greenGradientBtn" id="loginBtn" value="Войти" />
</div>
</div>
}
and second page
#model IncidentsDB.UI.Web.ViewModels.Account.LogOnModel
#{
ViewBag.Title = "Вход в систему";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<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())
{
<div class="restorePswdDivVisible">
<p>
Введите адрес электронной почты, <br />
который вы указывали при регистрации:
</p>
<div class="editor-label">
#Html.LabelFor(m => m.UserName)
</div>
<div class="editor-field noWrap">
#Html.TextBoxFor(m => m.UserName)
#Html.ValidationMessageFor(m => m.UserName)
</div>
<div class="loginErrorDiv noWrap" style="width: 150px">
</div>
<div>
<input type="submit" class="lightGreenGradientBtn restorePswdBtn" id="restorePswdBtn" value="Восстановить" style="margin-left: 150px" />
</div>
</div>
}
also I have model class which is general for two pages
namespace IncidentsDB.UI.Web.ViewModels.Account
{
public class LogOnModel
{
[Required(ErrorMessage="Укажите логин")]
[Display(Name = "NicName", ResourceType = typeof(PersonalRes))]
public string UserName { get; set; }
[Required(ErrorMessage = "Укажите пароль")]
[DataType(DataType.Password)]
[Display(Name = "Password", ResourceType = typeof(PersonalRes))]
public string Password { get; set; }
[Required(ErrorMessage = "Укажите e-mail")]
[DataType(DataType.EmailAddress)]
[Display(Name = "Email", ResourceType = typeof(PersonalRes))]
public string Email
{
get;
set;
}
[Display(Name = "Rememberme", ResourceType = typeof(PersonalRes))]
public bool RememberMe { get; set; }
}
}
so this code works fine in firefox and chrome, but doesn't in ie!
why?
thanks in advance!
Related
Say I want to modify a Movie in a view.
We can do it by the code.
#model MvcMovie.Models.Movie
#{
ViewBag.Title = "Edit";
}
<h2>Edit</h2>
#using (Html.BeginForm()) {
#Html.ValidationSummary(true)
<fieldset>
<legend>Movie</legend>
#Html.HiddenFor(model => model.ID)
<div class="editor-label">
#Html.LabelFor(model => model.Title)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Title)
#Html.ValidationMessageFor(model => model.Title)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.ReleaseDate)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.ReleaseDate)
#Html.ValidationMessageFor(model => model.ReleaseDate)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Genre)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Genre)
#Html.ValidationMessageFor(model => model.Genre)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Price)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Price)
#Html.ValidationMessageFor(model => model.Price)
</div>
<p>
<input type="submit" value="Save" />
</p>
</fieldset>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
However it is for one movie. But I have many movies say 5. The movie model is a list. How can I loop through it?
Your controller/view model":
public class MovieViewModel
{
public int ID { get; set; }
public string Title { get; set; }
}
public class HomeController : Controller
{
[HttpPost]
public ActionResult IndexValid3(IList<MovieViewModel> movieViewModel)
{
//set breakpoint here and update db here
return View(movieViewModel);
}
public ActionResult IndexValid3()
{
IList<MovieViewModel> list = new List<MovieViewModel>();
var movieViewModel = new MovieViewModel { ID = 1, Title = "title1"};
var movieViewModel2 = new MovieViewModel { ID = 1, Title = "title2"};
list.Add(movieViewModel);
list.Add(movieViewModel2);
return View(list);
}
View:
#model IList<Testy20161006.Controllers.MovieViewModel>
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>IndexValid3</title>
</head>
<body>
<div>
#using (Html.BeginForm())
{
<table>
#for (int i = 0; i < Model.Count(); i++)
{
<tr>
<td>#Html.TextBoxFor(m => Model[i].ID)</td>
<td>#Html.TextBoxFor(m => Model[i].Title)</td>
</tr>
}
</table>
<input type="submit" value="submit" />
}
</div>
</body>
I have a partial view which gets populated in modal body of my home page of MVC project. Partial view holds the login form as follows -
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="row">
<div class="col-xs-6">
<div class="well">
<div class="form-horizontal">
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
<div class="col-md-12">
#Html.LabelFor(model => model.UserEmailId, htmlAttributes: new { #class = "control-label" })
#Html.EditorFor(model => model.UserEmailId, new { htmlAttributes = new { #class = "form-control", placeholder = "example#gmail.com" } })
#Html.ValidationMessageFor(model => model.UserEmailId, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-12">
#Html.LabelFor(model => model.UserPassword, htmlAttributes: new { #class = "control-label" })
#Html.EditorFor(model => model.UserPassword, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.UserPassword, "", new { #class = "text-danger" })
</div>
</div>
<div class="checkbox">
<label>
<input type="checkbox" name="remember" id="remember"> Remember login
</label>
</div>
</div>
<button type="button" class="btn btn-success btn-block" onclick="location.href='#Url.Action("Login", "Home")'">
Login
</button>
</div>
</div>
<div class="col-xs-6">
<p class="lead">Sign up with</p>
<ul class="list-unstyled" style="line-height: 2">
<li><span class="fa fa-check text-success"></span> See all your orders</li>
<li><span class="fa fa-check text-success"></span> Fast re-order</li>
<li><span class="fa fa-check text-success"></span> Save your favorites</li>
<li><span class="fa fa-check text-success"></span> Fast checkout</li>
<li><span class="fa fa-check text-success"></span> Get a gift <small>(only new customers)</small></li>
<li><u>Read more</u></li>
</ul>
</div>
</div>
}
I am using a partial classes to define my data validations for the models(so that they wont get missed if I update my db first models) -
public class UserMetadata
{
[Display(Name ="Username")]
[EmailAddress(ErrorMessage ="Please enter your email address")]
[Required(ErrorMessage ="Required field")]
public string UserEmailId { get; set; }
[Display(Name ="Password")]
[DataType(DataType.Password)]
[Required(ErrorMessage = "Username is required")]
[StringLength(15, ErrorMessage = "Must be between 8 and 15 characters", MinimumLength = 8)]
public string UserPassword { get; set; }
}
The validations are not working on the client side. They are not getting triggered. Am I missing some script reference?
I already have "ClientValidationEnabled" set to true in my web.config.
Please help. Thanks!
Edit -
The following is all included in my layout -
<link href="https://fonts.googleapis.com/css?family=Montserrat:400,700" rel="stylesheet" type="text/css">
<link href='https://fonts.googleapis.com/css?family=Kaushan+Script' rel='stylesheet' type='text/css'>
<link href='https://fonts.googleapis.com/css?family=Droid+Serif:400,700,400italic,700italic' rel='stylesheet' type='text/css'>
<link href='https://fonts.googleapis.com/css?family=Roboto+Slab:400,100,300,700' rel='stylesheet' type='text/css'>
<script src="https://use.fontawesome.com/2d83329334.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.js"></script>
<script src="~/Scripts/jquery.validate.js"></script>
#Styles.Render("~/Content/css")
#Scripts.Render("~/bundles/modernizr")
Hi please check below code for reference
1. Model
public class UserMetadata
{
[Display(Name = "Username")]
[EmailAddress(ErrorMessage = "Please enter your email address")]
[Required(ErrorMessage = "Required field")]
public string UserEmailId { get; set; }
[Display(Name = "Password")]
[DataType(DataType.Password)]
[Required(ErrorMessage = "Username is required")]
[StringLength(15, ErrorMessage = "Must be between 8 and 15 characters", MinimumLength = 8)]
public string UserPassword { get; set; }
}
2. Controller
public class UserDataController : Controller
{
// GET: Contacts/UserData
public ActionResult Index()
{
var userData = new UserMetadata();
return View(userData);
}
}
view and Javascript
#model UserMetadata
#{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Index</h2>
#using (Html.BeginForm())
{
<div class="row">
<div class="col-xs-6">
<div class="well">
<div class="form-horizontal">
#Html.ValidationSummary(true, "", new { #class = "text- danger" })
<div class="form-group">
<div class="col-md-12">
#Html.LabelFor(model => model.UserEmailId, htmlAttributes: new { #class = "control-label" })
#Html.EditorFor(model => model.UserEmailId, new { htmlAttributes = new { #class = "form-control", placeholder = "example#gmail.com" } })
#Html.ValidationMessageFor(model => model.UserEmailId, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-12">
#Html.LabelFor(model => model.UserPassword, htmlAttributes: new { #class = "control-label" })
#Html.EditorFor(model => model.UserPassword, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.UserPassword, "", new { #class = "text-danger" })
</div>
</div>
<div class="checkbox">
<label>
<input type="checkbox" name="remember" id="remember"> Remember login
</label>
</div>
<button type="button" class="btn btn-success btn-block" onclick="loginUser();">
Login
</button>
</div>
</div>
</div>
</div>
}
<script>
function loginUser()
{
if($('form').valid())
{
//redirect to some action like window.location=somerootPath+/login/home
}
else
{
//not valid
}
}
OutPut
Ensure the highlighted js are loaded except jquery UI.
One way of solution is:
In the html editor add 'required' field as below
#Html.EditorFor(model => model.UserEmailId, new { htmlAttributes = new { #class = "form-control", placeholder = "example#gmail.com",#required="required" } })
and no need of Html.ValidationMessageFor() for this.
I have page that uses a partial view for a contact form, and the contact form is validated (so when I don't provide a required field, it redirect me to specific layout I create for this partial.)
Here is how my page is laid out:
Last image is a blank_layout I created for my partial view because if I don't do it, it changes all content like navbar and other parts of the page.
View Model:
public class ContactoViewModel
{
public IEnumerable<ProductosModel> ProductosListes { set; get; }
public String Descripcion { get; set; }
public String Id { get; set; }
[Required(ErrorMessage = "Es necesario que ingrese su nombre")]
public String Name { get; set; }
[Required(ErrorMessage = "Es necesario que ingrese su correo")]
[Email(ErrorMessage = "Ingrese un Email válido")]
public String Email { get; set; }
[Required(ErrorMessage = "Ingrese algún comentario por favor")]
[MinLength(10, ErrorMessage = "Es necesario que ingrese al menos 10 caracteres")]
public String Comments { get; set; }
}
Partial view:
#model DismedHmo.Models.ContactoViewModel
#{
Layout = "~/Views/Shared/Blank_Layout.cshtml";
}
#*<link href="~/Content/bootstrap.css" rel="stylesheet" />
<link href="~/Content/component.css" rel="stylesheet" />
<link href="~/Content/default.css" rel="stylesheet" />*#
<div class="row">
<!-- feedback -->
<article class="feedback">
#*<div class="title-contact">Deja un mensaje </div>*#
#using (Html.BeginForm("Contact_Partial", "ContactModels", FormMethod.Post))
{
<div class="title-margin">
#*<h6>Campos Requeridos*</h6>*#
</div>
<div class="input-group">
<div class="col-md-12">
<div class="relative">
<i class=" fa fa-user appointment-contact"></i>
<div class="contactlbl">
#Html.TextBoxFor(model => model.Name, new { #class = "form-control, txtboxexpand", #style = "width:100%", #placeholder = "Nombre*" })
#Html.ValidationMessageFor(model => model.Name, "", new { #class = "text-danger" })
</div>
</div>
</div>
</div>
<div class="input-group">
<div class="col-md-12">
<div class="relative">
<i class=" fa fa-envelope appointment-contact"></i>
<div class="contactlbl">
#Html.TextBoxFor(model => model.Email, new { #class = "form-control, txtboxexpand", #style = "width:100%", #placeholder = "Email*", #type = "email" })
#Html.ValidationMessageFor(model => model.Email, "", new { #class = "text-danger" })
</div>
</div>
</div>
</div>
<div class="input-group">
<div class="hidden-xs col-sm-12 col-md-12 col-lg-12">
<div class="relative">
<i class=" fa fa-align-left appointment-message"></i>
</div>
<div class="contactlbl">
#Html.TextAreaFor(model => model.Comments, new { #class = "form-control, txtareaexpand", #style = "width:100%", #placeholder = "Mensaje*" })
#Html.ValidationMessageFor(model => model.Comments, "", new { #class = "text-danger" })
</div>
</div>
</div>
<div class="input-group">
<div class="col-xs-12 hidden-sm hidden-md hidden-lg">
<div class="relative">
<i class=" fa fa-align-left appointment-message"></i>
</div>
<div class="contactlbl">
#Html.TextAreaFor(model => model.Comments, new { #class = "form-control, txtareaexpandxs", #style = "width:100%", #placeholder = "Mensaje*" })
#Html.ValidationMessageFor(model => model.Comments, "", new { #class = "text-danger" })
</div>
</div>
</div>
<div class="form-group margen-btn">
<div class="col-sm-12">
<input type="submit" value="Solicitar cotización" class="btn btn-contacto" />
</div>
</div>
}
</article>
</div>
Calling partial view on main page:
<div class="col-md-6">
#Html.Action("Contact_Partial", "ContactModels")
</div>
Controller:
[HttpPost]
public ActionResult Contact_Partial(ContactoViewModel model)
{
if (!ModelState.IsValid)
{
Danger("Su mensaje no fue enviado, porfavor intente de nuevo.");
return View();
}
using (var emailService = new EmailService())
{
emailService.SetRecipient("contacto#dismedhmo.com");
emailService.Contacto(model.Name, model.Email, model.Comments);
emailService.Send();
}
Success(string.Format("Tu mensaje ha sido enviado con exito."), true);
return RedirectToAction("Productos", "Productos");
}
public ActionResult MensajeEnviado()
{
return View();
}
I really want the validation page to be displayed where the contact form was. How can I do this?
I am developing an application in MVC using Smart Admin in which I use data annotations for validation purpose. My code is:
public class EmployeeDTO
{
[Key]
public int Id { get; set; }
[Required(ErrorMessage = "Name is required")]
[StringLength(50, ErrorMessage = "Name can accept maximum 50 characters.")]
[RegularExpression("^([a-zA-Z]{1}[a-zA-Z '-.(-,)-/&]*)$", ErrorMessage = "Please enter valid name.")]
public string Name { get; set; }
}
and my view is
<script src="~/SmartAdmin/js/libs/jquery-2.0.2.min.js"></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>
#model HBSeworld.Admin.DTO.EmployeeDTO
#{
ViewBag.Title = "Create";
}
<section class="jarviswidget" id="wid-id-1" data-widget-editbutton="false" data-widget-custombutton="false">
<header>
<span class="widget-icon"><i class="fa fa-user"></i></span>
<h2>Create Employee</h2>
</header>
<div>
<div class="jarviswidget-editbox">
</div>
<section class="widget-body no-padding">
#using (Html.BeginForm("Create", "Employee", FormMethod.Post, new { #id = "order-form", enctype = "multipart/form-data", #class = "smart-form" }))
{
#Html.ValidationSummary(true)
<fieldset>
<div class="row">
<section class="label col col-2" style="text-align: right">
#Html.LabelFor(model => model.Name)
</section>
<section class="col col-4">
<label class="input">
<i class="icon-append fa fa-user"></i>
#Html.TextBoxFor(model => model.Name, null, new { #placeholder = "Enter Name" })
#Html.ValidationMessageFor(model => model.Name)
</label>
</section>
</div>
</fieldset>
<div class="pull-right" style="margin-right: 5px; margin-bottom: 10px;">
<input type="submit" id="create" value="Create" class="btn btn-primary" style="height: 25px; width: 45px;" />
<input type="button" style="height:25px; width:45px;" value="Cancel" class="btn btn-default" onclick="window.location.href='#Url.Action("index") '"/>
</div>
}
</section>
</div>
</section>
Now, my question is that, when I click on Create button, data annotation message is displayed properly but at the same time the control goes to controller, instead it should be on same view and have to display data annotation message. How to prevent this? Any solution?
I am trying to post external URL for eg. (www.msn.com) on press of submit button.But when I do that none of my valdation works...it simply make an entry without any data in my external url
2. Also its not going to controller when i press submit button.
I don't know if I am doing anything wrong...
Here is my code for View:
#model n.Models.PopupDemoModel
<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("Demo","Home", FormMethod.Post, new { #action = "https://www.msn.com?encoding=UTF-8/post" }))
{
#Html.ValidationSummary(true)
<fieldset>
<input type=hidden name="oid" value="">
<input type=hidden name="retURL" value = "test" />
<input type="hidden" name="debug" value=1 />
<input type="hidden" name="debugEmail" value = "a#test.com" />
<div class="editor-label grid_2">
#Html.LabelFor(model => model.first_name)
</div>
<div class="editor-field grid_3">
#Html.TextBoxFor(model => model.first_name, new { #class = "demo-field-longer" })
</div>
<div class="grid_3 error long" style="margin-left:250px">
#Html.ValidationMessageFor(model => model.first_name)
</div>
<div class="clear"></div>
<div class="editor-label grid_2">
#Html.LabelFor(model => model.email)
</div>
<div class="editor-field grid_3">
#Html.TextBoxFor(model => model.email, new { #class = "demo-field-longer" })
</div>
<div class="grid_3 error long" style="margin-left:250px">
#Html.ValidationMessageFor(model => model.email)
</div>
<div class="clear"></div>
<div class="editor-label grid_2">
#Html.LabelFor(model => model.phone)
</div>
<div class="editor-field grid_3">
#Html.TextBoxFor(model => model.phone, new { #class = "demo-field-longer" })
</div>
<div class="grid_3 error long" style="margin-left:250px">
#Html.ValidationMessageFor(model => model.phone)
</div>
<div class="clear"></div>
<div class="editor-label grid_2">
#Html.LabelFor(model => model.company)
</div>
<div class="editor-field grid_3">
#Html.TextBoxFor(model => model.company, new { #class = "demo-field-longer" })
</div>
<div class="grid_3 error long" style="margin-left:250px">
#Html.ValidationMessageFor(model => model.company)
</div>
<div class="clear"></div>
<div class="clear"></div>
<div class="grid_2 sub-spacer"> </div>
<div class="editor-field grid_2 submit">
<input type="submit" value="Submit" id="demo-submit-button"/><br />
#ViewData["DemoMessage"]
</div>
</fieldset>
Here is my model:
public class PopupDemoModel
{
[Required]
[Email]
[DisplayName("Email address")]
public string email { get; set; }
[Required]
[DisplayName("Phone number")]
public string phone { get; set; }
[Required]
[DisplayName("Contact name")]
public string first_name { get; set; }
[Required]
[DisplayName("Company name")]
public string company { get; set; }
public string MessageSent
{
get { return "We'll contact you shortly."; }
}
}
It's doing exactly what you told it to.
The HTML <form> tag sends a POST request to the URL in the action attribute.
Html.BeginForm() creates a <form> tag with an action attribute that points to your controller.
When you set the action attribute explicitly, you replace the value from MVC and make it go directly to that URL.
If you want to do something with your data on server side before posting to another website, remove the action attribute so you will be posting to the same URL as at the beggining. In the action that is handling the POST from this form and doing the validation prepare your data. When you're ready, use WebRequest class to send this data to another website using POST method.