Goal: I have a page that I want to have a return url passed through the model of the view so upon completion of the form, it will return to the previous url. The page is a address validation and add it to the account as a saved address.
Flow of the page: You are presented with an address form to fill out. on completion, you will have a button that will call to a controller method that will verify with FedEx via API, and then if valid, it will let you save the address.
Issue: once you press the Verify Address button, it seems to have an issue with sending the form data to the controller.
HTTPGET:
public ActionResult AddShippingAddress(string strReturnURL)
{
// get states
ViewBag.states = GetStates();
DeliveryAddressModel model = new DeliveryAddressModel();
model.strReturnAddress = strReturnURL;
return View(model);
}
AddShippingAddress.chshtml
#model EcommerceWebsite.Models.Home.DeliveryAddressModel
#{
ViewBag.Title = "Shipping Address";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<br />
<div class="container">
<partial id="ValidateAddress"></partial>
#using (Html.BeginForm())
{
<h4>Shipping Address</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
<h5>Name</h5>
<div class="col-md-10">
#Html.EditorFor(model => model.strName, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.strName, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<h5>Attention To</h5>
<div class="col-md-10">
#Html.EditorFor(model => model.strAttnTo, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.strAttnTo, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<h5>Street</h5>
<div class="col-md-10">
#Html.EditorFor(model => model.strStreet1, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.strStreet1, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<h5>Street 2</h5>
<div class="col-md-10">
#Html.EditorFor(model => model.strStreet2, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.strStreet2, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<h5>City</h5>
<div class="col-md-10">
#Html.EditorFor(model => model.strCity, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.strCity, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#{
IEnumerable<SelectListItem> dataItems = ViewBag.states;
}
<div class="form-group">
<h5>State</h5>
<div class="col-md-10">
#Html.DropDownListFor(model => model.State.IntStateId, dataItems, "-- Select --", new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.State.IntStateId, "", new { #class = "text-danger" })
</div>
</div>
</div>
<div class="form-group">
<h5>Zip</h5>
<div class="col-md-10">
#Html.EditorFor(model => model.strZip, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.strZip, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<h5>Phone Number</h5>
<div class="col-md-10">
#Html.EditorFor(model => model.strPhoneNumber, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.strPhoneNumber, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<h5>Set as Default</h5>
<div class="col-md-10">
<div class="checkbox">
#Html.EditorFor(model => model.blnIsDefault)
#Html.ValidationMessageFor(model => model.blnIsDefault, "", new { #class = "text-danger" })
</div>
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<button type="button" class="btn btn-primary" data-ajax-method="get" data-toggle="ajax-modal"
data-url="#Url.Action("GetValidationOnAddress", new { model = Model })">
Verify Address
</button>
</div>
</div>
}
</div>
<script>
$(function () {
var PlaceHolderElement = $('#ValidateAddress');
$('button[data-toggle="ajax-modal"]').click(function (event) {
event.preventDefault();
var url = $(this).data('url');
// get the form containing the submit button
var form = $(this).closest('form')
// serialize all the fields in the form
var model = form.serialize();
// the the request to the url along with the form (model) data
$.get(url, model).done(function (data) {
PlaceHolderElement.html(data);
PlaceHolderElement.find('.modal').modal('show');
//$('#ValidateAddress').modal('show');
})
})
})
</script>
Here is the partial:
#model EcommerceWebsite.Models.Home.DeliveryAddressModel
<div class="modal fade" id="ValidateAddress">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title" id="ValidateAddressLabel">Validate Address</h4>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
#using (Html.BeginForm("AddShippingAddressToUser", "Home"))
{
#Html.HiddenFor(x => x.strName)
#Html.HiddenFor(x => x.strAttnTo)
#Html.HiddenFor(x => x.strStreet1)
#Html.HiddenFor(x => x.strStreet2)
#Html.HiddenFor(x => x.strCity)
#Html.HiddenFor(x => x.State.StrStateCode)
#Html.HiddenFor(x => x.State.StrStateName)
#Html.HiddenFor(x => x.State.IntStateId)
#Html.HiddenFor(x => x.strZip)
#Html.HiddenFor(x => x.strPhoneNumber)
#Html.HiddenFor(x => x.blnIsDefault)
<div class="modal-body">
<form action="Create">
<div class="form-group">
#if (Model.ErrorMessage == null)
{
<h5>#Model.strName</h5>
#if (Model.strAttnTo != null)
{<h5>#Model.strAttnTo</h5>}
<h5>#Model.strStreet1</h5>
#if (Model.strStreet2 != null)
{<h5>#Model.strStreet2</h5>}
<h5>#Model.strCity</h5>
<h5>#Model.State.StrStateCode</h5>
<h5>#Model.strZip</h5>
<h5>#Model.strPhoneNumber</h5>
<div class="modal-footer">
<button type="submit" value="Save" class="btn btn-primary">Save</button>
<button type="button" value="Edit" class="btn btn-secondary" data-dismiss="modal">Edit</button>
</div>
}
else
{
<h4>#Model.ErrorMessage</h4>
}
</div>
</form>
</div>
}
</div>
</div>
</div>
When all is said and done and the get validation button is pressed, it's supposed to send all the data to the controller and Verify the address with FedEx. But everything is null..
Now something to note, when I change the return of the httpget to return View(); everything works except it doesn't send the URL.
Update:
The AddShippingAddressToUser() hasn't even been called yet. The error lies somewhere in lines 101 - 102. Inside the button or the line 618 on the home controller.
Update: Here's the Model
public class DeliveryAddressModel
{
//[Required]
//[Display(Name = "First & Last Name")]
public string strName { get; set; }
//[Display(Name = "Attention To")]
public string strAttnTo { get; set; }
//[Required]
//[Display(Name = "Street 1")]
public string strStreet1 { get; set; }
//[Display(Name = "Street 2")]
public string strStreet2 { get; set; }
//[Required]
//[Display(Name = "City")]
public string strCity { get; set; }
//[Required]
//[Display(Name = "State")]
public Tstate State { get; set; }
//[Required]
//[Display(Name = "Zipcode")]
public string strZip { get; set; }
//[Required(ErrorMessage = "You must provide a phone number")]
//[Display(Name = "Phone Number")]
//[DataType(DataType.PhoneNumber)]
//[RegularExpression(#"^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$", ErrorMessage = "Not a valid phone number")]
public string strPhoneNumber { get; set; }
public bool blnIsDefault { get; set; }
public string ErrorMessage { get; set; }
public string strReturnAddress { get; set; }
}
First thing, since your form's function isnt a retrieval operation and a creational operation, use the http verb POST and not GET. Replace the HttpVerb filter above your action from HttpGet to HttpPost.
Second add this:
#using (Html.BeginForm("AddShippingAddressToUser", "Home", FormMethod.Post))
Alternatively,
#using (Html.BeginForm("AddShippingAddressToUser", "Home", FormMethod.Get))
Before your model in the action add: [FromQuery]
I am trying to validate the input of the user.
The validation works, because in my controller method the ModelState.IsValid is false when some input is invalid and is true when some input is valid.
The problem that I am having now is that the errormessage is not showing to the user. I thought that the empty string in the #Html.ValidationMessageFor should be automatically filled in by the error. That is correct, right?
The same code worked for my registration form, but not here.
Here is my form code:
#using (Html.BeginForm("ChangeProfile", "Account", FormMethod.Post))
{
<div class="form-group">
<label class="col-lg-3 control-label">Name:</label>
<div class="col-lg-9">
#Html.TextBoxFor(n => n.Name, new { #class = "form-control form-control-custom" })
#Html.ValidationMessageFor(n => n.Name, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<label class="col-lg-3 control-label">Email:</label>
<div class="col-lg-9">
<input disabled class="form-control form-control-custom" type="text" value="#Model.Email" />
</div>
</div>
<div class="form-group">
<label class="col-lg-3 control-label">New Password:</label>
<div class="col-lg-9">
#Html.TextBoxFor(n => n.Password, new { type = "password", placeholder = "New Password", #class = "form-control form-control-custom" })
#Html.ValidationMessageFor(n => n.Password, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<label class="col-lg-3 control-label">Confirm New Password:</label>
<div class="col-lg-9">
#Html.TextBoxFor(n => n.ConfirmPassword, new { type = "password", placeholder = "Confirm New Password", #class = "form-control form-control-custom" })
#Html.ValidationMessageFor(n => n.ConfirmPassword, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<label class="col-lg-3 control-label">Phone Number:</label>
<div class="col-lg-9">
#Html.TextBoxFor(n => n.PhoneNumber, new { #class = "form-control form-control-custom" })
#Html.ValidationMessageFor(n => n.PhoneNumber, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.ActionLink("DELETE ACCOUNT", "DeleteProfile", Model, new { #class = "btn btn-delete bg-primary" })
<input type="reset" class="btn btn-default" value="Cancel" style="float: right; margin-right: 15px;">
<input type="submit" class="btn btn-primary btn-custom" style="margin-right: 10px;" value="Save Changes">
</div>
}
Here is my controller method:
public IActionResult ChangeProfile(ProfileViewModel profileViewModel)
{
if (!ModelState.IsValid)
{
return RedirectToAction("Profile");
}
return View("Overview", accountService.ChangeProfile(profileViewModel));
}
And here is my ProfileViewModel:
public class ProfileViewModel
{
[Required]
public string Name { get; set; }
public string Email { get; set; }
[DataType(DataType.Password)]
public string Password { get; set; }
[DataType(DataType.Password)]
[Compare("Password", ErrorMessage = "The passwords do not match.")]
public string ConfirmPassword { get; set; }
[Required(ErrorMessage = "The Phone Number field is required.")]
[Phone(ErrorMessage = "The Phone Number field is not a valid phone number.")]
public string PhoneNumber { get; set; }
}
It's because when the model state is not valid you are doing a redirection with RedirectToAction("Profile"). By doing that you are loosing the "context" .
You should just re-render the View . With something like that :
return View("yourView", profileViewModel);
take care that your "view model" is not missing some properties (properties that are not in your form). If it is the case you must rebuild your viewmodel.
Hi I've got the following code in my controller (asp.net 4.5.1 mvc 5) that allows a user to register on my site. Everything was working fine but Ive added another controller and another service and now when ever I try to register all it does on submit is redirect back to the form blank again. After debugging, the post action method in controller below is never called
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Register(RegisterViewModel model)
{
if (ModelState.IsValid)
{
var user = new ApplicationUser { UserName = model.Email, Email = model.Email };
var result = await UserManager.CreateAsync(user, model.Password);
if (result.Succeeded)
{
UserManager.AddClaim(user.Id, new Claim(ClaimTypes.GivenName, model.FirstName));
var service = new GRCMemberService(HttpContext.GetOwinContext().Get<ApplicationDbContext>());
service.CreateGRCMember(model.FirstName, model.LastName, model.Address1, model.Address2, model.City, model.County, model.Postcode, model.Telephone, model.DateOfBirth, model.Dietary, model.CompLicenceNo, model.SelectedLicenceTypeId, model.NOKFirstName, model.NOKLastName, model.NOKTelephone, model.RelationshipTypeId, model.OtherOrgsGRC, model.OtherClubEvents, model.OtherOrgsOutside, user.Id);
//var currentUser = UserManager.FindByName(user.Id);
//var newrole = ("GRCMember");
//var roleresult = UserManager.AddToRole(currentUser.Id, newrole);
await SignInManager.SignInAsync(user, isPersistent:false, rememberBrowser:false);
// For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771
// Send an email with this link
// string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);
// var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
// await UserManager.SendEmailAsync(user.Id, "Confirm your account", "Please confirm your account by clicking here");
return RedirectToAction("Index", "Home");
}
AddErrors(result);
}
// If we got this far, something failed, redisplay form
return View(model);
}
instead, the get action method below is always called every time I submit the form:
[AllowAnonymous]
public ActionResult Register()
{
return View();
}
Any idea what's wrong?
Below is my ViewModel and View code.
ViewModel
public class RegisterViewModel
{
[Required]
[Display(Name = "First Name")]
[StringLength(160, ErrorMessage = "First Name cannot be longer than 160 characters.")]
public string FirstName { get; set; }
[Required]
[Display(Name = "Last Name")]
[StringLength(160, ErrorMessage = "Last Name cannot be longer than 160 characters.")]
public string LastName { get; set; }
[Required]
[Display(Name = "Address 1")]
[StringLength(160, ErrorMessage = "Address1 cannot be longer than 160 characters.")]
public string Address1 { get; set; }
[Display(Name = "Address 2")]
[StringLength(160, ErrorMessage = "Address2 cannot be longer than 160 characters.")]
public string Address2 { get; set; }
[Required]
[Display(Name = "City")]
[StringLength(100, ErrorMessage = "City cannot be longer than 100 characters.")]
public string City { get; set; }
[Display(Name = "County")]
[StringLength(100, ErrorMessage = "County cannot be longer than 100 characters.")]
public string County { get; set; }
[Required]
[Display(Name = "PostCode")]
[StringLength(10, ErrorMessage = "Postcode cannot be longer than 10 characters.")]
public string Postcode { get; set; }
[Required]
[Display(Name = "Telephone")]
[StringLength(20, ErrorMessage = "Telephone cannot be longer than 20 characters.")]
public string Telephone { get; set; }
[StringLength(20, ErrorMessage = "Competition Licence Number cannot be longer than 20 characters.")]
[Display(Name = "Licence Number")]
public string CompLicenceNo { get; set; }
[Display(Name = "Licence Type")]
public int? SelectedLicenceTypeId { get; set; }
[StringLength(200, ErrorMessage = "Competition Licence Number cannot be longer than 20 characters.")]
[Display(Name = "Dietary Requirements - For events")]
public string Dietary { get; set; }
[Required]
[StringLength(100, ErrorMessage = "Next of Kin Name cannot be longer than 100 characters.")]
[Display(Name = "Next of kin First Name")]
public string NOKFirstName { get; set; }
[Required]
[StringLength(100, ErrorMessage = "Next of Kin Name cannot be longer than 100 characters.")]
[Display(Name = "Next of kin Last Name")]
public string NOKLastName { get; set; }
[Required]
[StringLength(20, ErrorMessage = "Next of Kin Telephone cannot be longer than 20 characters.")]
[Display(Name = "Next of kin Telephone")]
public string NOKTelephone { get; set; }
[Display(Name = "Next of kin Relationship")]
public int? RelationshipTypeId { get; set; }
[Required]
[Display(Name = "Date of Birth")]
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:dd/mm/yyyy}", ApplyFormatInEditMode = true)]
public DateTime DateOfBirth { get; set; }
[Display(Name = "Allow other organisations on Grass Roots Clicks to contact you?")]
public bool OtherOrgsGRC { get; set; }
[Display(Name = "Allow other clubs you are a member of or ones whose events you enter to contact you?")]
public bool OtherClubEvents { get; set; }
[Display(Name = "Allow other organisations outside of Grass Roots Clicks that we are working with to contact you?")]
public bool OtherOrgsOutside { get; set; }
[Required]
[EmailAddress]
[Display(Name = "Email")]
public string Email { get; set; }
[EmailAddress]
[Display(Name = "Confirm email")]
[Compare("Email", ErrorMessage = "Your email and confirmation email do not match.")]
public string ConfirmEmail { 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; }
}
View
#model GRCWebApp.Models.RegisterViewModel
#{
ViewBag.Title = "Register";
}
<h2 class="text-success">#ViewBag.Title</h2>
<div class="row">
<div class="col-md-7">
<div class="well bs-component">
<form class="form-horizontal">
<fieldset>
<section id="loginForm">
#using (Html.BeginForm("Register", "Account", FormMethod.Post, new { #class = "form-horizontal", role = "form" }))
{
#Html.AntiForgeryToken()
<hr />
#Html.ValidationSummary("", new { #class = "text-danger" })
<h3 class="text-success col-md-offset-1">Name & Address</h3>
<div class="form-group">
<div class="row">
<div class="col-md-3 col-md-offset-1">
#Html.LabelFor(model => model.FirstName, htmlAttributes: new { #class = "control-label" })
#Html.EditorFor(model => model.FirstName, new { htmlAttributes = new { #class = "form-control", placeholder = "John" } })
#Html.ValidationMessageFor(model => model.FirstName, "", new { #class = "text-danger" })
</div>
<div class="col-md-4 col-md-offset-2">
#Html.LabelFor(model => model.LastName, htmlAttributes: new { #class = "control-label" })
#Html.EditorFor(model => model.LastName, new { htmlAttributes = new { #class = "form-control", placeholder = "Smith" } })
#Html.ValidationMessageFor(model => model.LastName, "", new { #class = "text-danger" })
</div>
</div>
<div class="row">
<div class="col-md-5 col-md-offset-1">
#Html.LabelFor(model => model.Address1, htmlAttributes: new { #class = "control-label" })
#Html.EditorFor(model => model.Address1, new { htmlAttributes = new { #class = "form-control", placeholder = "1 Apple Road" } })
#Html.ValidationMessageFor(model => model.Address1, "", new { #class = "text-danger" })
</div>
<div class="col-md-5">
#Html.LabelFor(model => model.Address2, htmlAttributes: new { #class = "control-label" })
#Html.EditorFor(model => model.Address2, new { htmlAttributes = new { #class = "form-control", placeholder = "Neighbourhood" } })
#Html.ValidationMessageFor(model => model.Address2, "", new { #class = "text-danger" })
</div>
</div>
<div class="row">
<div class="col-md-5 col-md-offset-1">
#Html.LabelFor(model => model.City, htmlAttributes: new { #class = "control-label" })
#Html.EditorFor(model => model.City, new { htmlAttributes = new { #class = "form-control", placeholder = "Some Town" } })
#Html.ValidationMessageFor(model => model.City, "", new { #class = "text-danger" })
</div>
<div class="col-md-5">
#Html.LabelFor(model => model.County, htmlAttributes: new { #class = "control-label" })
#Html.EditorFor(model => model.County, new { htmlAttributes = new { #class = "form-control", placeholder = "Someshire" } })
#Html.ValidationMessageFor(model => model.County, "", new { #class = "text-danger" })
</div>
</div>
<div class="row">
<div class="col-md-3 col-md-offset-1">
#Html.LabelFor(model => model.Postcode, htmlAttributes: new { #class = "control-label" })
#Html.EditorFor(model => model.Postcode, new { htmlAttributes = new { #class = "form-control", placeholder = "AA1 2BB" } })
#Html.ValidationMessageFor(model => model.Postcode, "", new { #class = "text-danger" })
</div>
</div>
</div>
<h3 class="text-success col-md-offset-1">Contact Details</h3>
<div class="form-group">
<div class="row">
<div class="col-md-4 col-md-offset-1">
#Html.LabelFor(model => model.Telephone, htmlAttributes: new { #class = "control-label" })
#Html.EditorFor(model => model.Telephone, new { htmlAttributes = new { #class = "form-control", placeholder = "01234 567890" } })
#Html.ValidationMessageFor(model => model.Telephone, "", new { #class = "text-danger" })
</div>
</div>
<div class="row">
<div class="col-md-4 col-md-offset-1">
#Html.LabelFor(model => model.Email, htmlAttributes: new { #class = "control-label" })
#Html.EditorFor(model => model.Email, new { htmlAttributes = new { #class = "form-control", placeholder = "me#provider.com" } })
#Html.ValidationMessageFor(model => model.Email, "", new { #class = "text-danger" })
</div>
<div class="col-md-4 col-md-offset-1">
#Html.LabelFor(model => model.ConfirmEmail, htmlAttributes: new { #class = "control-label" })
#Html.EditorFor(model => model.ConfirmEmail, new { htmlAttributes = new { #class = "form-control", placeholder = "me#provider.com" } })
#Html.ValidationMessageFor(model => model.ConfirmEmail, "", new { #class = "text-danger" })
</div>
</div>
</div>
<h3 class="text-success col-md-offset-1">Competition Licence</h3>
<div class="form-group">
<div class="row">
<div class="col-md-4 col-md-offset-1">
#Html.LabelFor(model => model.CompLicenceNo, htmlAttributes: new { #class = "control-label" })
#Html.EditorFor(model => model.CompLicenceNo, new { htmlAttributes = new { #class = "form-control", placeholder = "123456" } })
#Html.ValidationMessageFor(model => model.CompLicenceNo, "", new { #class = "text-danger" })
</div>
<div class="col-md-3 col-md-offset-1">
#Html.LabelFor(model => model.SelectedLicenceTypeId, htmlAttributes: new { #class = "control-label" })
#Html.EditorFor(model => model.SelectedLicenceTypeId, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.SelectedLicenceTypeId, "", new { #class = "text-danger" })
</div>
</div>
</div>
<h3 class="text-success col-md-offset-1">Personal Details</h3>
<h4 class="text-success col-md-offset-1">Why do we need this information?</h4>
<p>To make it easier for you to enter events here on Grass Roots Clicks we gatther certain information that we can then populate into your entry. Why do we need a date of birth? Organisers gain great benefit form knowing what ages are taking part in their events. We dont share your date of birth, we use your current age to help the organisers and also tailor the entry form to you e.g. if your under 18 we'll ask you for parental permission for some events.</p>
<div class="form-group">
<div class="row">
<div class="col-md-3 col-md-offset-1">
#Html.LabelFor(model => model.DateOfBirth, htmlAttributes: new { #class = "control-label" })
#Html.EditorFor(model => model.DateOfBirth, new { htmlAttributes = new { #class = "form-control", placeholder = "01/12/80" } })
#Html.ValidationMessageFor(model => model.DateOfBirth, "", new { #class = "text-danger" })
</div>
</div>
<div class="row">
<div class="col-md-4 col-md-offset-1">
#Html.LabelFor(model => model.NOKFirstName, htmlAttributes: new { #class = "control-label" })
#Html.EditorFor(model => model.NOKFirstName, new { htmlAttributes = new { #class = "form-control", placeholder = "Jane" } })
#Html.ValidationMessageFor(model => model.NOKFirstName, "", new { #class = "text-danger" })
</div>
<div class="col-md-4 col-md-offset-1">
#Html.LabelFor(model => model.NOKLastName, htmlAttributes: new { #class = "control-label" })
#Html.EditorFor(model => model.NOKLastName, new { htmlAttributes = new { #class = "form-control", placeholder = "Smith" } })
#Html.ValidationMessageFor(model => model.NOKLastName, "", new { #class = "text-danger" })
</div>
</div>
<div class="row">
<div class="col-md-4 col-md-offset-1">
#Html.LabelFor(model => model.NOKTelephone, htmlAttributes: new { #class = "control-label" })
#Html.EditorFor(model => model.NOKTelephone, new { htmlAttributes = new { #class = "form-control", placeholder = "07234 567890" } })
#Html.ValidationMessageFor(model => model.NOKTelephone, "", new { #class = "text-danger" })
</div>
<div class="col-md-4 col-md-offset-1">
#Html.LabelFor(model => model.RelationshipTypeId, htmlAttributes: new { #class = "control-label" })
#Html.EditorFor(model => model.RelationshipTypeId, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.RelationshipTypeId, "", new { #class = "text-danger" })
</div>
</div>
<div class="row">
<div class="col-md-7 col-md-offset-1">
#Html.LabelFor(model => model.Dietary, htmlAttributes: new { #class = "control-label" })
#Html.EditorFor(model => model.Dietary, new { htmlAttributes = new { #class = "form-control", placeholder = "Vegetarian" } })
#Html.ValidationMessageFor(model => model.Dietary, "", new { #class = "text-danger" })
</div>
</div>
</div>
<h3 class="text-success col-md-offset-1">Password</h3>
<div class="form-group">
<div class="row">
<div class="col-md-4 col-md-offset-1">
#Html.LabelFor(model => model.Password, htmlAttributes: new { #class = "control-label" })
#Html.EditorFor(model => model.Password, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Password, "", new { #class = "text-danger" })
</div>
<div class="col-md-4 col-md-offset-1">
#Html.LabelFor(model => model.ConfirmPassword, htmlAttributes: new { #class = "control-label" })
#Html.EditorFor(model => model.ConfirmPassword, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.ConfirmPassword, "", new { #class = "text-danger" })
</div>
</div>
</div>
<h3 class="text-success col-md-offset-1">Contact</h3>
<div class="form-group">
<div class="row">
<div class="col-md-9 col-md-offset-1">
#Html.LabelFor(model => model.OtherOrgsGRC, htmlAttributes: new { #class = "control-label" })
</div>
<div class="col-md-1">
#Html.CheckBoxFor(model => model.OtherOrgsGRC, new { #checked = "checked" })
#Html.ValidationMessageFor(model => model.OtherOrgsGRC, "", new { #class = "text-danger" })
</div>
</div>
<div class="row">
<div class="col-md-9 col-md-offset-1">
#Html.LabelFor(model => model.OtherClubEvents, htmlAttributes: new { #class = "control-label" })
</div>
<div class="col-md-1">
#Html.CheckBoxFor(model => model.OtherClubEvents, new { #checked = "checked" })
#Html.ValidationMessageFor(model => model.OtherClubEvents, "", new { #class = "text-danger" })
</div>
</div>
<div class="row">
<div class="col-md-9 col-md-offset-1">
#Html.LabelFor(model => model.OtherOrgsOutside, htmlAttributes: new { #class = "control-label" })
</div>
<div class="col-md-1">
#Html.CheckBoxFor(model => model.OtherOrgsOutside, new { #checked = "checked" })
#Html.ValidationMessageFor(model => model.OtherOrgsOutside, "", new { #class = "text-danger" })
</div>
</div>
</div>
<div class="form-group">
<div class="col-md-10 col-md-offset-1">
<input type="submit" value="Register" class="btn btn-success btn-lg" />
</div>
</div>
}
</section>
</fieldset>
</form>
</div>
</div>
<div class="col-md-4 panel panel-success">
<div class="panel-heading">
<h3 class="panel-title " align="center">Use another service to register</h3>
</div>
#Html.Partial("_ExternalLoginsListPartial", new GRCWebApp.Models.ExternalLoginListViewModel { ReturnUrl = ViewBag.ReturnUrl })
</div>
</div>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
#Scripts.Render("~/bundles/bootstrap")
<script type="text/javascript">
$("#DateOfBirth").datepicker({
format: "dd/mm/yyyy",
startDate: "-120y",
endDate: "-10y",
startView: 2,
calendarWeeks: true,
defaultViewDate: { year: 1975, month: 01, day: 01 }
});
</script>
}
I fixed the problem by removing the form, fieldset and section tags at the beginning of the view.
Thanks to ekad for helping debug the problem
I am using the default form for registering a user with Identity, with slightly changed HTML only.
#using (Html.BeginForm("Register", "Account", FormMethod.Post, new { #class = "form-horizontal", role = "form" }))
{
#Html.AntiForgeryToken()
#Html.ValidationSummary("", new { #class = "text-danger" })
// Do something with something here
<div class="form-group">
#Html.LabelFor(m => m.Fornavn, new { #class = "col-md-2 control-label" })
<div class="col-md-10">
#Html.TextBoxFor(m => m.Fornavn, new { #class = "form-control", autocomplete = "off" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(m => m.Etternavn, new { #class = "col-md-2 control-label" })
<div class="col-md-10">
#Html.TextBoxFor(m => m.Etternavn, new { #class = "form-control", autocomplete = "off" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(m => m.Email, new { #class = "col-md-2 control-label" })
<div class="col-md-10">
#Html.TextBoxFor(m => m.Email, new { #class = "form-control", autocomplete = "off" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(m => m.Password, new { #class = "col-md-2 control-label" })
<div class="col-md-10">
#Html.PasswordFor(m => m.Password, new { #class = "form-control", autocomplete = "off" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(m => m.ConfirmPassword, new { #class = "col-md-2 control-label" })
<div class="col-md-10">
#Html.PasswordFor(m => m.ConfirmPassword, new { #class = "form-control", autocomplete = "off" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" class="btn btn-primary" value="Registrer" />
</div>
</div>
}
It's using this register model, and I added a new prop which I just called "something".
How can I set the value of "something" in my view so that when the form is submitted I can access my "something" in the controller?
Thank you vey much
public class RegisterViewModel
{
public bool something { get; set; }
[Required]
[StringLength(50, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 2)]
[Display(Name = "Fornavn")]
public string Fornavn { get; set; }
[Required]
[StringLength(50, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 2)]
[Display(Name = "Etternavn")]
public string Etternavn { get; set; }
[Required]
[EmailAddress]
[Display(Name = "Email")]
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 = "Passord")]
public string Password { get; set; }
[DataType(DataType.Password)]
[Display(Name = "Gjenta passord")]
[Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
public string ConfirmPassword { get; set; }
}
If you're setting the value in your controller you can add a hidden field to your form using the HiddenFor() input extension:
#Html.HiddenFor(m => m.something)
or alternatively if you just want to hardcode the value. you can use:
#Html.Hidden("something", true)
I have a simple example.
Two class. User and Company like :
public class User() {
public int UserID { get; set; }
[Display(Name = "User name")]
public string Name { get; set; }
[Display(Name = "Company")]
public int CompanyID { get; set; }
public virtual Company Company { get; set; }
}
public class Company() {
public int CompanyID { get; set; }
[Display(Name = "Company")]
public string Name { get; set; }
public virtual ICollection<User> Users { get; set; }
}
My problem is in the Create and the Edit views of the User.
The label for "Name" is displayed correctly in "User name" but the label for "CompanyID" stay displayed at "CompanyID" (the drop down list is created correctly with all Companies). I want the label display "Company" like I make it in the class.
I've try to change my view but all I do block compilation so I'm lost.
I'm begginer in MVC so excuse me if it easy to do but I don't see it.
Edit (add Create View code) :
#model Intranet3.Models.User
#{
ViewBag.Title = "Add a user";
}
#using (Html.BeginForm(null, null, FormMethod.Post, htmlAttributes: new { #class = "form-horizontal form-bordered" })) {
#Html.AntiForgeryToken()
<div class="row-fluid">
<div class="span12">
<div class="box">
<div class="box-title">
<h3>
<i class="icon-table"></i>
New
</h3>
</div>
<div class="box-content nopadding">
<div class="form-horizontal">
#Html.MyValidationSummary()
<div class="control-group #Html.ClassErrorFor(model => model.Name)">
#Html.LabelFor(model => model.Name, new { #class = "control-label" })
<div class="controls">
#Html.EditorFor(model => model.Name)
#Html.MyValidationMessageFor(model => model.Name)
</div>
</div>
<div class="control-group #Html.ClassErrorFor(model => model.CompanyID)">
#Html.LabelFor(model => model.CompanyID, "CompanyID", new { #class = "control-label" })
<div class="controls">
#Html.DropDownList("CompanyID", String.Empty)
#Html.MyValidationMessageFor(model => model.CompanyID)
</div>
</div>
<div class="form-actions">
<button type="submit" class="btn btn-primary">Create</button>
<button onclick="location.href='#Url.Action("Index","User")'" type="button" class="btn">Cancel</button>
</div>
</div>
</div>
</div>
</div>
</div>
}
Edit 2 :
Problem solved by delete the string force in Labels.
So this :
#Html.LabelFor(model => model.CompanyID, "CompanyID", new { #class = "control-label" })
Need to be
#Html.LabelFor(model => model.CompanyID, new { #class = "control-label" })
Why have u passed parameter CompanyId
#Html.LabelFor(model => model.CompanyID, "CompanyID", new { #class = "control-label" })
Should be
#Html.LabelFor(model => model.CompanyID, new { #class = "control-label" })
#Html.TextBoxFor(c => c.CompanyID, new { data_bind = "text:Contacts.FirstName", #class = "form-control" })
If you have knockoutjs binding