I have created the register page on mvc3 razor. I want to put the validation on user notification field. Below is my code.
[Required]
[Display(Name = "Student Notification ?")]
[Range(typeof(bool), "true", "true", ErrorMessage = "You gotta tick the box!")]
public Boolean UserNotification { get; set; }
Below is my register page view
<div class="editor-label">
#Html.LabelFor(model => model.UserNotification)
</div>
<div class="editor-label">
#Html.CheckBoxFor(model =>model.UserNotification)
#Html.ValidationMessageFor(model => model.UserNotification)
</div>
<p>
<input type="submit" value="Register" />
</p>
So when i will click the button, there should be validation message there ..
You need to change your datatype of the property UserNotification. Change:
public Boolean UserNotification { get; set; }
To:
public bool UserNotification { get; set; }
There is a lot difference between Boolean and bool.
Related
Basically, i have a form with a textbox, radio button and a check box control. now i face problem with the checkbox control when i submit my page
I have a model like this
public class PersonDetails
{
public int personID { get; set; }
public string PersonName { get; set; }
public string Gender { get; set; }
public List<Education> Education { get; set; }
public string EmailID { get; set; }
public string Address { get; set; }
}
public class Education
{
public string Qualification { get; set; }
public bool Checked { get; set; }
public List<Education> GetQualification()
{
return new List<Education>{
new Education {Qualification="SSC",Checked=false},
new Education {Qualification="HSC",Checked=false},
new Education {Qualification="Graduation",Checked=false},
new Education {Qualification="PostGraduation",Checked=false}
};
}
}
and i have a view like this
#using (Html.BeginForm("GetDetails", "User", FormMethod.Post, new { id = "person-form" }))
{
<div class="col-xs-12">
<label>Person Name</label>
#Html.TextBoxFor(x => x.PersonName)
</div>
<div class="col-xs-12">
<label>Gender</label>
#Html.RadioButtonFor(x => x.Gender, "Male")
#Html.RadioButtonFor(x => x.Gender, "Female")
</div>
<div class="col-xs-12">
<label>Education</label>
#{
Html.RenderPartial("Qualification", new LearnAuthentication.Controllers.Education().GetQualification());
}
</div>
<div class="col-xs-12">
<input type="submit" value="Submit" />
</div>
}
and the partial view like this
#model List<LearnAuthentication.Controllers.Education>
<br />
#for (int i = 0; i < Model.Count(); i++)
{
#Html.HiddenFor(x => Model[i].Qualification)
#Html.CheckBoxFor(x => Model[i].Checked)
#Html.DisplayFor(x => Model[i].Qualification)
<br />
}
and my action method is this
[HttpPost]
public ActionResult GetDetails(PersonDetails personDetails)
{
return View();
}
now when i run my app i tend to get all the information but when i submit the page i get this property with null values
public List Education { get; set; }
can any of you guys help me on what i am doing wrong or could you direct me to the right path on how to achieve this.
Your use of a partial to generate the controls for Education is generating inputs such as
<input type="hidden" name="[0].Qualification" ... />
<input type="hidden" name="[1].Qualification" ... />
but in order to bind, they need to have name attributes which match your model
<input type="hidden" name="Education[0].Qualification" ... />
<input type="hidden" name="Education[1].Qualification" ... />
Rename you partial to Education.cshtml (to match the name of the class) and move it to your /Views/Shared/EditorTemplates folder (or /Views/yourControllerName/EditorTemplates if you want a specific template just for that controller)
Then change the partial to
#model LearnAuthentication.Controllers.Education
#Html.HiddenFor(m => m.Qualification)
#Html.LabelFor(m => m.Checked)
#Html.CheckBoxFor(m => m.Checked)
#Html.DisplayFor(m => m.Qualification)
and in the main view replace
<label>Education</label>
#{ Html.RenderPartial("Qualification", new LearnAuthentication.Controllers.Education().GetQualification()); }
with
<span>Education</span> // its not a label
#Html.EditorFor(m => m.Education)
which will correctly generate the correct html for each item in your collection
Side note: Other alternatives which would work would be to change the POST method signature to
[HttpPost]
public ActionResult GetDetails(PersonDetails personDetails List<Education> educationDetails)
or to pass the HtmlFieldPrefix to the partial as explained in getting the values from a nested complex object that is passed to a partial view
I am building an ASP.Net MVC 3 Web application using Entity Framework 4.1. To perform validation within one of my Views which accepts a ViewModel. I am using Data Annotations which I have placed on the properties I wish to validate.
ViewModel
public class ViewModelShiftDate
{
public int shiftDateID { get; set; }
public int shiftID { get; set; }
[DisplayName("Start Date")]
[Required(ErrorMessage = "Please select a Shift Start Date/ Time")]
public DateTime? shiftStartDate { get; set; }
[DisplayName("Assigned Locum")]
public int assignedLocumID { get; set; }
public SelectList AssignedLocum { get; set; }
}
View
#using (Html.BeginForm())
{
#Html.ValidationSummary(true)
<br />
<div class="editor-label">
#Html.LabelFor(model => model.shiftStartDate)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.shiftStartDate, new { #readonly = "readonly" })
#Html.ValidationMessageFor(model => model.shiftStartDate)
</div>
<br />
<div class="editor-label">
#Html.LabelFor(model => model.assignedLocumID)
</div>
<div class="editor-field">
#Html.DropDownListFor(model => model.assignedLocumID, Model.AssignedLocum)
#Html.ValidationMessageFor(model => model.assignedLocumID)
</div>
<br />
<p>
<input type="submit" value="Save" />
</p>
<br />
}
The SelectList 'AssignedLocum' is passed into my View for a DropDownList, and the item selected is assigned to the property 'assignedLocumID'.
As you can see from my ViewModel, the only required field is 'shiftStartDate', however, when I hit the Submit button in my View, the drop down list 'AssignedLocum' also acts a required field and will not allow the user to submit until a value is selected.
Does anyone know why this property is acting as a required field even though I have not tagged it to be so?
Thanks.
Try to use default value for dropdown (for example "Please select")
#Html.DropDownListFor(model => model.assignedLocumID, Model.AssignedLocum, "Please select")
I am new MVC user and I am trying to make shopping cart as following MVC Music Store tutorial
I am trying to pass the radiobutton value which is different price types through actionlink.
Is it possible to pass the value with productId?
When I click the link, it will call 'AddToCart' method.
Could you help me? thanks.
Product model
namespace MvcApplication2.Models
{
public class Product
{
[Key] public int productId { get; set; }
public int categoryId { get; set; }
[Required(ErrorMessage = "Product model name is required")]
public String model { get; set; }
[DisplayFormat(DataFormatString = "{0:0.#}")]
public decimal displaySize { get; set; }
public String processor { get; set; }
public int ramSize { get; set; }
public int capacity { get; set; }
public String colour { get; set; }
public String description { get; set; }
public decimal price { get; set; }
public decimal threeDayPrice { get; set; }
public decimal aWeekPrice { get; set; }
public decimal twoWeekPrice { get; set; }
public decimal aMonthPrice { get; set; }
public decimal threeMonthPrice { get; set; }
public decimal sixMonthPrice { get; set; }
//public decimal sixMonthPrice { get { return price * 0.25M; } }
public int stock { get; set; }
public virtual Category Category { get; set; }
}
}
details.cshtml
#model MvcApplication2.Models.Product
<td>
Rental Period: <br />
#using (Html.BeginForm())
{
<div class="display-label">
#Html.RadioButtonFor(model => model.price, Model.threeDayPrice)
3 day: £#Model.threeDayPrice
</div>
<div class="display-label">
#Html.RadioButtonFor(model => model.price, Model.aWeekPrice)
1 week: £#Model.aWeekPrice
</div>
<div class="display-label">
#Html.RadioButtonFor(model => model.price, #Model.twoWeekPrice)
2 week: £#Model.twoWeekPrice
</div>
<div class="display-label">
#Html.RadioButtonFor(model => model.price, #Model.twoWeekPrice)
1 month: £#Model.twoWeekPrice
</div>
<div class="display-label">
#Html.RadioButtonFor(model => model.price, #Model.threeMonthPrice)
3 month: £#Model.threeMonthPrice
</div>
<div class="display-label">
#Html.RadioButtonFor(model => model.price, #Model.sixMonthPrice)
6 month: £#Model.sixMonthPrice
</div>
}
</td>
</tr>
</table>
<p class="button" style="margin-left:200px; width:90px;">
//Is it possible to submit the selected radiobutton value through this?
#Html.ActionLink("Add to cart", "AddToCart", "ShoppingCart", new { id = Model.productId }, "")
</p>
---Added controller---
ShoppingCartController.cs
public ActionResult AddToCart(int id)
{
// Retrieve the product from the database
var addedProduct = db.Product
.Single(product => product.productId == id);
// Add it to the shopping cart
var cart = ShoppingCart.GetCart(this.HttpContext);
cart.AddToCart(addedProduct);
// Go back to the main store page for more shopping
return RedirectToAction("Index");
}
Just use a submit button instead of an ActionLink. This way all the input values will be sent to the controller when you submit the form:
#model MvcApplication2.Models.Product
<td>
Rental Period: <br />
#using (Html.BeginForm("AddToCart", "ShoppingCart", new { id = Model.productId }, FormMethod.Post))
{
<div class="display-label">
#Html.RadioButtonFor(model => model.price, Model.threeDayPrice)
3 day: £#Model.threeDayPrice
</div>
<div class="display-label">
#Html.RadioButtonFor(model => model.price, Model.aWeekPrice)
1 week: £#Model.aWeekPrice
</div>
<div class="display-label">
#Html.RadioButtonFor(model => model.price, #Model.twoWeekPrice)
2 week: £#Model.twoWeekPrice
</div>
<div class="display-label">
#Html.RadioButtonFor(model => model.price, #Model.twoWeekPrice)
1 month: £#Model.twoWeekPrice
</div>
<div class="display-label">
#Html.RadioButtonFor(model => model.price, #Model.threeMonthPrice)
3 month: £#Model.threeMonthPrice
</div>
<div class="display-label">
#Html.RadioButtonFor(model => model.price, #Model.sixMonthPrice)
6 month: £#Model.sixMonthPrice
</div>
<button type="submit">Add to cart</button>
}
</td>
Because you say you are new right off the bat I'm going to tell you that the way you are going about this is not the best way to achieve what you are trying to achieve.
Putting a submit button at the bottom of the form will get the data to post and bind to Product if you change the top of the form to
#using (Html.BeginForm("AddToCart", "WHATEVERYOURCONTROLLERISCALLED"))
but I think you are missing a few key points here.
There are some conventions that you seem to be ignoring
ShoppingCart.cs should be named ShoppingCartController.cs and appear in the controllers folder of your project
Instead of naming each price on the model you can use a list of prices options and display them on the form as a series of radio buttons while putting the mutually exclusive choice. for example.
The Model
public class Product{
// remove all the different price properties.
// other properties go here...And while you are at it Use Pascal case for property names Eg. displaySize would be DisplaySize but I guess that is up to you.
[Required]
public string PriceChoice { get; set; }
}
The Controller
public class ShoppingCartController : Controller
{
public ActionResult Details(int productId)
{
// get the product from the database
var model = Database.GetProductById(productId);
// set a default if you want
model.PriceChoice = "a";
return View(model);
}
[HttpPost]
public ActionResult AddToCart(Product model)
{
// do whatever you need to do
return RedirectToAction("Details", new { id = model.Id });
}
}
The View
#using (Html.BeginForm())
{
<div>A: #Html.RadioButtonFor(x => x.PriceChoice , "a")</div>
<div>B: #Html.RadioButtonFor(x => x.PriceChoice , "b")</div>
#Html.ValidationMessageFor(x => x.PriceChoice )
<input type="submit" value="OK" />
}
Now that's all very abridged and basic so I hope you get the gist of it.
Also you'll find some value in reading this Post Redirect Get So while it doesn't strictly apply to what you are doing it will explain the structure of the code you are reading in the examples where you see RedirectToAction.
Now if you want to do this really cleverly you will have to learn some javascript and issue an Ajax command.
Hope this helps
I thought I have asked this before, but I am not finding it. I am making partial view for a form so I can use it in multiple places. Here is one short snippet:
#model Permits.Domain.Entities.PermitRequest
#using (Html.BeginForm())
{
#Html.ValidationSummary(true)
<div class="editor-label">
#Html.LabelFor(model => model.JobAddress)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.JobAddress)
#Html.ValidationMessageFor(model => model.JobAddress)
</div>
<p>
<input type="submit" value="Submit request" />
</p>
</fieldset>
}
My model looks like:
public class PermitRequest
{
[Description("Job address")]
public string JobAddress { get; set; }
}
Why would my label still be "JobAddress" instead of "Job Address" (with the space)? I feel like I am missing something obvious.
[DisplayName("Job address")]
public string JobAddress { get; set; }
or if you prefer:
[Display(Name = "Job address")]
public string JobAddress { get; set; }
Both set the DisplayName property of the ModelMetadata which is used by the LabelFor helper.
Here's my model's property:
[Required(ErrorMessage = "Debe escribir su fecha de nacimiento")]
[Display(Name = "Fecha de Nacimiento")]
[DataType(DataType.Date)]
public DateTime DateOfBirth { get; set; }
In my AccountController, I create a new object of this model and pass it to the View:
<div class="editor-label">
#Html.LabelFor(model => model.DateOfBirth)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.DateOfBirth)
#Html.ValidationMessageFor(model => model.DateOfBirth)
</div>
Remember, at this point this is a Create form. The model's properties have no values.
However, this is rendered in my HTML.
Is there some way to tell the view engine to not render anything in this field?
If you change your definition to a Nullable, then it'll start off as null and no value will be displayed if one isn't set (which by default it isn't).
public DateTime? DateOfBirth { get; set; }