I have a jQuery selectable widget in my razor view which displayed as an and updated from a comma separated string in SQL Server table just like below:
<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.
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:
@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. 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. Any help please?
Please note that I am passing values from view to another controller action method, here is the action method.
public ActionResult AddToCart(int id,int SelectedQuantity, string SelectedSizes, string AvailableColors)
{
var addedProduct = dbContext.Products
.Single(product => product.ProductID == id);
var cart = ShoppingCart.GetCart(this.HttpContext);
cart.AddToCart(addedProduct, SelectedQuantity, AvailableColors,SelectedSizes);
return RedirectToAction("Index");
}
What I have tried:
I tried to add another property to my view model as below with [Required] Data annotation.
public class SizeColorViewModel
{
[HiddenInput(DisplayValue = false)]
[Key]
public int ProductID { get; set; }
[Display(Name="Select Size")]
[Required(ErrorMessage="Please select a size")]
public string AvailableSizes { get; set; }
[Required]
public string SelectedSizes { get; set; }
}
But even that i couldn't validate that field any idea?