简体   繁体   English

如何在ASP.NET MVC剃刀视图中验证hiddenfor字段?

[英]How to validate hiddenfor fields in asp.net mvc razor views?

I have a jQuery selectable widget in my razor view which displayed as an <ol> and updated from a comma separated string in SQL Server table just like below: 我在剃刀视图中有一个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>

The above as mentioned displays set of colors like (Red, Green, Purple and etc) list which is of-course selectable and the user can only pick one from the list at a time. 上面提到的显示了一组颜色(如(红色,绿色,紫色等)列表),这些列表当然是selectable ,并且用户一次只能从列表中选择一种。
I passed the selected list item value in a hidden field which is then passed to controller action method with below script. 我在隐藏字段中传递了所选列表项的值,然后使用以下脚本将其传递给控制器​​操作方法。

<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> 

In my form I've a HiddenFor razor attribute to pass selected list item value to the controller as below: 在我的表单中,我具有一个HiddenFor razor属性,将选定的列表项值传递给控制器​​,如下所示:

@Html.HiddenFor(m => m.AvailableColors, new { @id = "selectedcolor" })

Now here is something that I am stuck and couldn't find a solution searching over internet. 现在,这是我遇到的问题,无法找到通过Internet搜索的解决方案。 I want that if no item selected the validation should occur and the validation message for the AvailableColors should appear but I have no idea how to do it. 我希望如果没有选择任何项目,则应该进行验证,并且应该显示AvailableColors的验证消息,但是我不知道该怎么做。 Any help please? 有什么帮助吗?
EDIT: Here is the controller action method that I am passing data to: // GET: /Store/AddToCart/5 编辑:这是我要将数据传递到的控制器操作方法:// 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");
}

You might consider adding a new property to store the selected item text(string) in your view model and decorate it with [Required] data annotation. 您可能考虑添加一个新属性,以在视图模型中存储所选项目的文本(字符串),并使用[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.
}

and have this hidden form in your form 并在您的表单中包含此隐藏表单

@using (Html.BeginForm("AddToCart","ShoppingCart"))
{
    @Html.HiddenFor(f => f.SelectedColor)
    @Html.ValidationMessageFor(f=>f.SelectedColor)
    <input type="submit" class="btn btn-default" value="Submit" />
}

When you submit the form ModelState.IsValid will be false and if you return the model back to view, you will see the error message for SelectedColor 当您提交表单ModelState.IsValid将为false,并且如果您将模型返回查看,则会看到SelectedColor的错误消息。

[HttpPost]
public ActionResult AddToCart(AddToCartViewModel model)
{
  if(ModelState.IsValid)
  {
    //continue saving and return something
  }
  return View(model);
}

If you have client side unobtrusive validation, It won't work with hidden field by default. 如果您具有客户端非侵入式验证,则默认情况下它将不适用于隐藏字段。 One workaround you can do is to keep the field as an input, but set the visibility to hidden. 您可以采取的一种解决方法是将该字段保留为输入,但将可见性设置为隐藏。 Then the client side validation will also show the validation error message. 然后,客户端验证还将显示验证错误消息。

@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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM