kk1076 kk1076 - 1 year ago 120
C# Question

Validation of @Html.Textbox in MVC4

I use an update action to update based on the input from the @Html.Textbox.

@using (Html.BeginForm("Update", "Shopping", new { UserID = Request.QueryString["UserID"] }, FormMethod.Post, new { id = "myForm" }))
@Html.Hidden("id", @Request.QueryString["UserID"] as string)
@Html.Hidden("productid", item.ProductID as string)
@Html.TextBox("Quantity", item.Quantity)
@Html.ValidationMessage("Quantity", "*")
@Html.Hidden("unitrate", item.Rate)
<input type="submit" value="Update" />

and In My Model class

[Required(ErrorMessage = "Quantity is required.")]
[Display(Name = "Quantity")]
[Range(2, 100, ErrorMessage = "There is not enough inventory for the product to fulfill your order.")]
public int? Quantity { get; set; }

The problem is I m not getting the validation message when the textbox is empty.
But when I use @Html.TextBoxFor

@Html.TextBoxFor(modelItem => item.Quantity)
@Html.ValidationMessageFor(modelitem => item.Quantity)

I am getting the validation message. and my update action is not working.

Here I have two options.

1. How to pass the textbox name "qty" in @Html.TextboxFor ?? (or)

2. How to get the validation message in @Html.Textbox() using @Html.ValidationMessage()

Any suggestions ..

My Update Action

public ActionResult Update(string id, string productid, int Quantity, decimal unitrate)
if (ModelState.IsValid)
int _records = UpdatePrice(id, productid, Quantity, unitrate);
if (_records > 0)
return RedirectToAction("Index1", "Shopping", new { UserID = Request.QueryString["UserID"] });
ModelState.AddModelError("","Can Not Update");
return View("Index1");

Answer Source

you have the answer in your question, when you use

@Html.TextBoxFor(modelItem => item.Quantity)
@Html.ValidationMessageFor(modelitem => item.Quantity)

you get the error message becasue the MVC model validation works on the name attributes as @Mystere Man said in the comments you are defying all the conventions and conventions is what MVC is all about, either change the property name in your model or use it as it is in the view if you want to leverage the MVC's model validation.

Not entirely relevant but a good read.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download