【问题标题】:Store Multiple checkboxes values in MVC在 MVC 中存储多个复选框值
【发布时间】:2016-02-20 16:00:24
【问题描述】:

下面是在数据库中添加新产品的完整代码,它可以工作。

I've 3 tables "Product","Category" and "SubCategory".

I've 5 Categories "Electronics","Clothing","Sports","Books" and "Others".

我想添加 3 个尺寸的复选框:小、中和大,我希望这些复选框隐藏,除非我从下拉列表中选择“服装”类别。当我从类别下拉列表中选择服装时,尺寸复选框应该会出现,因此我可以选择 size:small 复选框,或者可能同时是 size:small 和 size:medium 复选框,我希望将其存储在数据库中。我不认为复选框的两个值都可以存储在数据库的一行中。

示例

productid = 1

product name= polo t-shirt

sizes: small & medium (both checkboxes are checked)

在查看产品详细信息以添加到购物车功能时,我希望在下拉列表中显示可用尺寸。

我有一个产品模型

public int ProductId { get; set; }

    public int? CategoryId { get; set; }

    [Required]
    [StringLength(50)]
    public string Name { get; set; }

    public string Description { get; set; }

    public decimal? Price { get; set; }

    public int? Quantity { get; set; }

    [StringLength(100)]
    public string ImagePath { get; set; }

    public DateTime? Submitted { get; set; }

    public int? StoreId { get; set; }

    [StringLength(50)]
    public string DeliveryDate { get; set; }

    [StringLength(50)]
    public string ShippingCharges { get; set; }

    public int? SubCategoryId { get; set; }

    public int? ProvinceId { get; set; }

    public int? CityId { get; set; }

    [StringLength(50)]
    public string PaymentMethod { get; set; }

    public virtual Category Category { get; set; }

    public virtual City City { get; set; }

    public virtual Province Province { get; set; }

    public virtual Store Store { get; set; }

    public virtual SubCategory SubCategory { get; set; }

产品负责人

[HttpPost]
    [Authorize(Roles = "StoreOwner")]
    [ValidateAntiForgeryToken]
    public ActionResult AddProduct(HttpPostedFileBase file)
    {
        List<string> DeliveryDate = new List<string>();
        DeliveryDate.Add("1-2 Days");
        DeliveryDate.Add("3-5 Days");
        DeliveryDate.Add("1 Week");
        SelectList dd = new SelectList(DeliveryDate);
        ViewBag.DeliveryDate = dd;

        List<string> PaymentMethods = new List<string>();
        PaymentMethods.Add("Cash on Delivery");
        SelectList pm = new SelectList(PaymentMethods);
        ViewBag.PaymentMethods = pm;

        IEnumerable<SelectListItem> provinces = db.Provinces.Select(c => new SelectListItem
        {
            Value = c.ProvinceId.ToString(),
            Text = c.ProvinceName

        });
        ViewBag.ProvinceId = provinces;

        IEnumerable<SelectListItem> cities = db.Cities.Select(c => new SelectListItem
        {
            Value = c.CityId.ToString(),
            Text = c.CityName

        });
        ViewBag.CityId = cities;

        IEnumerable<SelectListItem> categories = db.Categories.Select(c => new SelectListItem
        {
            Value = c.CategoryId.ToString(),
            Text = c.Name

        });

        ViewBag.CategoryId = categories;

        IEnumerable<SelectListItem> subcategories = db.SubCategories.Select(c => new SelectListItem
        {
            Value = c.SubCatId.ToString(),
            Text = c.SubCatName

        });
        ViewBag.SubCategoryId = subcategories;


        IEnumerable<SelectListItem> stores = db.Stores.Select(c => new SelectListItem
        {
            Value = c.StoreId.ToString(),
            Text = c.Name

        });
        ViewBag.Stores = stores;

         if (file != null)
            {
                string ImagePath = System.IO.Path.GetFileName(file.FileName);
                string physicalPath = Server.MapPath("~/ProductImages/" + ImagePath);

                file.SaveAs(physicalPath);

                //save new record in database
                Product newRecord = new Product();
                newRecord.Name = Request.Form["Name"];
                newRecord.CategoryId = Convert.ToInt32(Request.Form["CategoryId"]);
                newRecord.SubCategoryId = Convert.ToInt32(Request.Form["SubCategoryId"]);
                newRecord.StoreId = Convert.ToInt32(Request.Form["Stores"]);
                newRecord.Description = Request.Form["Description"];
                newRecord.Price = Convert.ToDecimal(Request.Form["Price"]);
                newRecord.Quantity = Convert.ToInt32(Request.Form["Quantity"]);
                newRecord.ProvinceId = Convert.ToInt32(Request.Form["ProvinceId"]);
                newRecord.CityId = Convert.ToInt32(Request.Form["CityId"]);
                newRecord.ShippingCharges = Request.Form["ShippingCharges"];
                newRecord.DeliveryDate = Request.Form["DeliveryDate"];
                newRecord.PaymentMethod = Request.Form["PaymentMethods"];
                newRecord.ImagePath = ImagePath;
                newRecord.Submitted = DateTime.Now;
                db.Products.Add(newRecord);
                db.SaveChanges();
                return RedirectToAction("OwnerManage","Manage");
            }

        return View();
    }

查看

@using (Html.BeginForm("AddProduct", "Store", FormMethod.Post, new { enctype = "multipart/form-data",   @class = "form-horizontal", role = "form" }))
{
@Html.AntiForgeryToken()
<h4>Create a new product.</h4>
<hr />
@Html.ValidationSummary(true)
<div class="form-group">
    @Html.LabelFor(m => m.Name, new { @class = "col-md-2 control-label", data_val_required = "required" })
    <div class="col-md-10">
        @Html.TextBoxFor(m => m.Name, new { @class = "form-control" })
        @Html.ValidationMessageFor(m=>m.Name)
    </div>
</div>
<div class="form-group">
    @Html.LabelFor(m => m.Description, new { @class = "col-md-2 control-label" })
    <div class="col-md-10">
        @Html.TextAreaFor(m => m.Description, new { @class = "form-control" })
    </div>
</div>
<div class="form-group">
    @Html.LabelFor(m => m.CategoryId, new { @class = "col-md-2 control-label" })
    <div class="col-md-10">
        @Html.DropDownListFor(x => x.CategoryId, ViewBag.CategoryId as SelectList, new { @class = "CssCategory" })
    </div>
</div>
<div class="form-group">
    @Html.LabelFor(m => m.SubCategoryId, new { @class = "col-md-2 control-label subcatshow" })
    <div class="col-md-10">
        @Html.DropDownListFor(x => x.SubCategoryId, ViewBag.SubCategoryId as SelectList, new { @class = "CssSubCategory" })
    </div>
</div>

<div class="form-group">
    @Html.LabelFor(m => m.StoreId, new { @class = "col-md-2 control-label" })
    <div class="col-md-10">
        @Html.DropDownList("Stores", "Select a Value")
    </div>
</div>

<div class="form-group">
    @Html.LabelFor(m => m.ProvinceId, new { @class = "col-md-2 control-label" })
    <div class="col-md-10">
        @Html.DropDownListFor(x => x.ProvinceId, ViewBag.ProvinceId as SelectList, new { @class = "CssProvince" })

    </div>
</div>

<div class="form-group">
    @Html.LabelFor(m => m.CityId, new { @class = "col-md-2 control-label cityshow" })
    <div class="col-md-10">
        @Html.DropDownListFor(x => x.CityId, ViewBag.CityId as SelectList, new { @class = "CssCity" })
    </div>
</div>

<div class="form-group">
    @Html.LabelFor(m => m.Price, new { @class = "col-md-2 control-label" })
    <div class="col-md-10">
        @Html.TextBoxFor(x => x.Price, new { @class = "form-control" })
    </div>
</div>

<div class="form-group">
    @Html.LabelFor(m => m.Quantity, new { @class = "col-md-2 control-label" })
    <div class="col-md-10">
        @Html.TextBoxFor(x => x.Quantity, new { @class = "form-control" })
    </div>
</div>

<div class="form-group">
    @Html.LabelFor(m => m.DeliveryDate, new { @class = "col-md-2 control-label" })
    <div class="col-md-10">
        @Html.DropDownList("DeliveryDate", ViewBag.DeliveryDate as SelectList)
    </div>
</div>

<div class="form-group">
    @Html.LabelFor(m => m.ShippingCharges, new { @class = "col-md-2 control-label" })
    <div class="col-md-10">
        @Html.TextBoxFor(x => x.ShippingCharges, new { @class = "form-control" })
    </div>
</div>

<div class="form-group">
    @Html.LabelFor(m => m.PaymentMethod, new { @class = "col-md-2 control-label" })
    <div class="col-md-10">
        @Html.DropDownList("PaymentMethods", ViewBag.PaymentMethods as SelectList)
    </div>
</div>

<div class="form-group">
    @Html.LabelFor(m => m.ImagePath, new { @class = "col-md-2 control-label" })
    <div class="col-md-10">
        <input type="file" name="file" id="file" style="width: 100%;" />
    </div>
</div>

<div class="form-group">
    <div class="col-md-offset-2 col-md-10">
        <input type="submit" class="btn btn-default" value="Create Product" />
    </div>
</div>

}

【问题讨论】:

  • 真的有必要在问题中转储所有这些代码吗?只需显示相关代码,您将更有机会看到它。参考How to create a Minimal, Complete, and Verifiable example
  • 至于如何解决这个问题,一种选择是使您的属性成为具有[Flags] 属性的枚举或将值存储为逗号分隔列表的字符串,并使用视图模型表示您然后映射回属性的复选框

标签: c# asp.net-mvc checkbox asp.net-mvc-5


【解决方案1】:

你可以做很多事情。一对夫妇是:

A.您可以将名为 small medium 和 large 的 bool? 类型的三个属性添加到您的产品对象中。

B.您可以创建一个具有三个尺寸属性的尺寸对象,也是 bool? 类型,然后将尺寸对象添加到您的产品对象中。

然后在视图上,您​​可以使用 jquery 根据他们选择的产品类型来切换他们的可见性。

这完全取决于您要如何处理存储它。

A.如果您必须只使用表中的一行,则可以存储一个字符串以解析,如“S;L”并通过“;”分割/加入。

B.您还可以做一些荒谬的事情并创建一个新表,其中包含所有可能的选择变化,并为每个表分配一个 ID,并将 ID 传递到另一个表的单行中。

C.我会亲自创建一个新表,将产品 ID 作为外键,每个尺寸有 3 列作为bool

但是,我不确定哪种方式会被视为“良好做法”。

【讨论】:

  • 我会尝试创建一个新表。感谢您提出的建议!
  • 不客气。如您所知,由于您使用的是 MVC,因此您可以大量清理控制器。就绑定对象而言,MVC 为您做了很多工作。例如,在你的控制器的帖子中,不要只接收HttpPostedFileBase file,还要接收你的产品模型。 public ActionResult AddProduct(HttpPostedFileBase file, Product newProduct)
猜你喜欢
  • 2017-01-08
  • 1970-01-01
  • 2018-03-29
  • 2018-12-18
  • 1970-01-01
  • 2015-02-22
  • 2019-02-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多