![](/img/trans.png)
[英]How to validate fields using jquery in asp.net mvc 3 razor
[英]How to validate hiddenfor fields in asp.net mvc razor views?
我在剃刀视图中有一个jQuery selectable
小部件,它显示为<ol>
并从SQL Server表中的逗号分隔的字符串更新,如下所示:
<ol class="ui-selectable" style="width:auto" id="selectable1">
@{
var color = Model.AvailableColors.Split(',');
foreach (var clr in color)
{
<li class="btn red-mint" style="margin: 10px 0">@clr</li>
}
}
</ol>
上面提到的显示了一组颜色(如(红色,绿色,紫色等)列表),这些列表当然是selectable
,并且用户一次只能从列表中选择一种。
我在隐藏字段中传递了所选列表项的值,然后使用以下脚本将其传递给控制器操作方法。
<script type="text/javascript">
$(document).ready(function () {
$("#selectable1").selectable({
selected: function (event, ci) {
$(ci.selected).siblings().removeClass("ui-selected");
$("#selectedcolor").val($("#selectable1>li.ui-selected").html());
}
});
});
</script>
在我的表单中,我具有一个HiddenFor
razor属性,将选定的列表项值传递给控制器,如下所示:
@Html.HiddenFor(m => m.AvailableColors, new { @id = "selectedcolor" })
现在,这是我遇到的问题,无法找到通过Internet搜索的解决方案。 我希望如果没有选择任何项目,则应该进行验证,并且应该显示AvailableColors
的验证消息,但是我不知道该怎么做。 有什么帮助吗?
编辑:这是我要将数据传递到的控制器操作方法:// GET:/ Store / AddToCart / 5
public ActionResult AddToCart(int id,int SelectedQuantity, string SelectedSizes, string AvailableColors)
{
// Retrieve the album from the database
var addedProduct = dbContext.Products
.Single(product => product.ProductID == id);
// Add it to the shopping cart
var cart = ShoppingCart.GetCart(this.HttpContext);
cart.AddToCart(addedProduct, SelectedQuantity, AvailableColors,SelectedSizes);
// Go back to the main store page for more shopping
return RedirectToAction("Index");
}
您可能考虑添加一个新属性,以在视图模型中存储所选项目的文本(字符串),并使用[Required]
数据注释对其进行修饰。
public class AddToCartViewModel
{
public int ProductId { set;get;}
[Required]
public int SelectedQuantity { set;get;}
[Required]
pubilc string SelectedColor { set;get;}
// Add other properties as needed.
}
并在您的表单中包含此隐藏表单
@using (Html.BeginForm("AddToCart","ShoppingCart"))
{
@Html.HiddenFor(f => f.SelectedColor)
@Html.ValidationMessageFor(f=>f.SelectedColor)
<input type="submit" class="btn btn-default" value="Submit" />
}
当您提交表单ModelState.IsValid
将为false,并且如果您将模型返回查看,则会看到SelectedColor
的错误消息。
[HttpPost]
public ActionResult AddToCart(AddToCartViewModel model)
{
if(ModelState.IsValid)
{
//continue saving and return something
}
return View(model);
}
如果您具有客户端非侵入式验证,则默认情况下它将不适用于隐藏字段。 您可以采取的一种解决方法是将该字段保留为输入,但将可见性设置为隐藏。 然后,客户端验证还将显示验证错误消息。
@using (Html.BeginForm("AddToCart","ShoppingCart"))
{
@Html.TextBoxFor(f => f.SelectedColors, new {style="visibility:hidden;"})
@Html.ValidationMessageFor(f=>f.SelectedColor)
<input type="submit" class="btn btn-default" value="Submit" />
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.