Validation stopped working on use of formmethod.post - asp.net-mvc

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.

Related

Unable to pass RadioButton group selected value to Controller

I have a ViewModel defined as:
public class Fixtures
{
public int Id { get; set; }
public string HomeTeam { get; set; }
public string AwayTeam { get; set; }
public string HomeTeamCode { get; set; }
public string AwayTeamCode { get; set; }
public string League { get; set; }
public bool Home { get; set; }
public bool Draw { get; set; }
public bool Away { get; set; }
public string FixturePrediction { get; set; }
}
My view displays a list of these fixtures and for each fixture, I have a radio button grouping. I need some way of passing the selected radio button for each fixture to my Post method. My View and controller are as below:
View:
<div class="container">
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
for (int i = 0; i < Model.Count(); i++)
{
#Html.HiddenFor(model => model[i].Id)
<div class="col-sm-6">
<div class="panel panel-primary panel-fixture">
<div class="panel-heading text-center fixturetitle">
#Html.DisplayFor(model => model[i].HomeTeam) v #Html.DisplayFor(model => model[i].AwayTeam)
#Html.HiddenFor(model => model[i].HomeTeam)
#Html.HiddenFor(model => model[i].AwayTeam)
</div>
<div class="panel-body">
<div class="container-fluid">
<div class="row">
<div class="col-xs-4 text-center">
<img src="~/Content/Images/#string.Concat(Model[i].HomeTeamCode, ".png")" class="fixturecrest" />
<div class="text-center">
#Html.DisplayFor(model => model[i].HomeTeamCode)
#Html.HiddenFor(model => model[i].HomeTeamCode)
</div>
</div>
<div class="col-xs-4 text-center">
<label class="text-center">
V <br />
</label>
</div>
<div class="col-xs-4 text-center">
<img src="~/Content/Images/#string.Concat(Model[i].AwayTeamCode, ".png")" class="fixturecrest" />
<div class="text-center">
#Html.DisplayFor(model => model[i].AwayTeamCode)
#Html.HiddenFor(model => model[i].AwayTeamCode)
</div>
</div>
</div>
<hr />
<div class="row">
<div class="text-center" role="group" aria-label="Fixture Prediction">
<div class="col-xs-4 text-center">
<button type="button" class="btn btn-xs btn-default">
HOME
#Html.RadioButtonFor(model => model[i].FixturePrediction, Model[i].Home, new { #Name = Model[i].Id })
#Html.HiddenFor(model => model[i].FixturePrediction)
<span class="glyphicon glyphicon-check"></span>
</button>
</div>
<div class="col-xs-4 text-center">
<button type="button" class="btn btn-xs btn-default">
DRAW
#Html.RadioButtonFor(model => model[i].FixturePrediction, Model[i].Draw, new { #Name = Model[i].Id })
#Html.HiddenFor(model => model[i].FixturePrediction)
<span class="glyphicon glyphicon-check"></span>
</button>
</div>
<div class="col-xs-4 text-center">
<button type="button" class="btn btn-xs btn-default">
AWAY
#Html.RadioButtonFor(model => model[i].FixturePrediction, Model[i].Away, new { #Name = Model[i].Id })
#Html.HiddenFor(model => model[i].FixturePrediction)
<span class="glyphicon glyphicon-check"></span>
</button>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
}
<input type="submit" value="Confirm Predictions" class="btn btn-success" />
}
</div>
Post Method in Controller:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Test(IEnumerable<Fixtures> test)
{
if (ModelState.IsValid)
{
}
return RedirectToAction("Test");
}
My field FixturePrediction is always null and I have attempted several variations of the 'radiobuttonfor' shown above.
All I need is to assign a value to FixturePrediction based on which radiobutton is selected. What am I missing?
Thanks in advance.
I think what you are trying to do is this, I am not sure why you are doing it the way you are doing it, but this is how you would implement Html.RadioButtonFor, it takes the model prop, and the value, you can add as many buttons as you want, and the selected radio value will be passed as the value for your model prop
#Html.RadioButtonFor(model => model[i].FixturePrediction, "Home")
#Html.RadioButtonFor(model => model[i].FixturePrediction, "Draw")
#Html.RadioButtonFor(model => model[i].FixturePrediction, "Away")
Another example

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

MVC Client side validation are not working in partial view

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.

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")
}

How to get a form value in another form value submission

I had username and password in first form and retrieve password in another form , in which i want userame entered in first form in submission of second form.
#model Network.Models.LoginDetail
<script type="text/javascript">
</script>
#{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<p>
Please enter your user name and password. #Html.ActionLink("Register", "Register") if you don't have an account.
</p>
#using (Html.BeginForm("Index","Student",FormMethod.Post)) {
<div>
<fieldset>
<legend>Account Information</legend>
<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.Password)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Password)
#Html.ValidationMessageFor(model => model.Password)
</div>
<p>
<input type="submit" value="Log in" style="width: 200px"/>
</p>
#ViewBag.Message
</fieldset>
</div>
}
#using (Html.BeginForm("RetrievePassword","Student",FormMethod.Post)) {
<p>
Forgot password? <input type="submit" onclick="updateUsername();"value="Click Here" style="width: 150px"/> Entering your username to retrieve your password.
</p>
#Html.HiddenFor(model => model.Username)
}
How can we acheive this, i tried in javascript capturing of username in hiddenfield but not working.
Or can form within form be used to acheive this.
Please provide a solution.
Thanks,
Michaeld
At the post method of "Index" action in "Stundent" controller you will be able to get the value either in formcollection or in LoginDetail object form.
Example:
public ActionRestult Index(FormCollection FC)
{
string UserName = FC["Username"];
string Password = FC["Password"];
}
Or Alternatively
public ActionRestult Index(LoginDetail obj)
{
string UserName = obj.Username;
string Password = obj.Password;
}
This will fix your concern.

Resources