多个复选框,用于在数据库表C#MVC3中选择和保存值

时间:2012-06-30 03:49:28

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

我正在处理的项目要求我在表单上放置复选框,以便用户可以选择多个项目。我可以将这些作为bool放在单独的列中,但复选框值可能会更改或需要添加。所以我创建了一个表,其中包含这些复选框的名称,然后将其列出。我的问题是;如何将这些值放入另一个与客户一致的表中。应如何妥善处理?

该视图具有公司名称和记录ID / AuditSchedule / details / 208 我已经读过,在列中放置多个值不是一个好习惯,但我还有其他选择吗?

非常感谢!

我对客户表的含义是ProductType的字段。这与任何事情无关。还有另一个包含产品类型的表,我想将其列为复选框。我在这两个表之间没有任何关系。对我来说似乎不应该有,但请纠正我,让我知道是否应该。因此,当选中一个复选框时,我希望将该值(ProductName)放在ProductType字段中以逗号分隔的customer表中。

这是客户或时间表:

    public class AuditSchedule
{
    public virtual int AuditScheduleID { get; set; }
    public virtual Nullable<DateTime> audit_completed_date { get; set; }
    public virtual string gl_cmp_key { get; set; }
    public virtual string audit_year { get; set; }
    public virtual string ar_ship_key { get; set; }
    public virtual string ar_ship_name { get; set; }
    public virtual string im_adres_city { get; set; }
    public virtual string im_adres_state { get; set; }
    public virtual string audit_type { get; set; }
    public virtual string audit_no { get; set; }
    public virtual string audit_group { get; set; }
    public virtual string Footage { get; set; }
    public virtual string Rolling3MosFootage { get; set; }
    public virtual string snp_SalesRep8 { get; set; }
    public virtual string epg_sales_rep_accountable { get; set; }
    public virtual string tech_service_rep { get; set; }
    public virtual string audit_done_by { get; set; }
    public virtual Nullable<DateTime> audit_recieved_date { get; set; }
    public virtual string audit_notes { get; set; }
    public virtual string audit_pdf { get; set; }
    public virtual string updated { get; set; }
    public virtual string hidden { get; set; }
    public virtual string en_stats_key { get; set; }
    public virtual string Control_ID { get; set; }
    public virtual Nullable<DateTime> audit_date { get; set; }
    public virtual string contacts_present { get; set; }
    public virtual string audit_furnished_to { get; set; }
    public virtual string spacer_type { get; set; }
}

以下是产品表:

    public class SpacerProduct
{
    public int SpacerProductID { get; set; }
    public string SpacerBrand { get; set; }
    public string SpacerName { get; set; }
}

希望这有帮助

视图是AuditSchedules的表单类型编辑,只有几个地方可以填写。这部分有效。添加复选框到视图是我迷路的地方。我创建了一个局部视图,用于填充复选框的ToList,然后将其添加到表单中。不知道如何在表格中得到结果。

Tohid的问题: 我对一些事情有疑问。首先是ViewModel我假设这只是你的Models目录的名称空间,我的只是模型。 _db.getAuditScheduleById不在我的实体中,你解释说我可能不得不采取另一种方式。对我来说,这将是_db.AuditSchedules它出现在下拉列表但不喜欢它所以我把它改成了 更新于07/02/2012     viewModel.AuditScheduleInstance = _db.AuditSchedules.Single(r =&gt; r.AuditScheduleID == id);

我仍然在

上遇到问题
_db.GetAvailableSpacerProducts()

我的实体中没有反映这一点的任何内容,我不知道如何更改它。可能是我改变了另一个但不确定的东西。

2012年7月5日更新

这是QQAEntities:

命名空间QQAForm.Models

{
public class QQAEntities : DbContext
   {
    public DbSet<AuditSchedule> AuditSchedules { get; set; }
    public DbSet<Category> Categories { get; set; }
    public DbSet<SubCategory> SubCategories { get; set; }
    public DbSet<MainQuestion> MainQuestions { get; set; }
    public DbSet<Suggestion> Suggestions { get; set; }        
    public DbSet<DocumentLink> DocumentLinks { get; set; }
    public DbSet<Audit> Audits { get; set; }
    public DbSet<AuditData> AuditDatas { get; set; }
    public DbSet<SpacerProduct> SpacerProducts { get; set; }
    public DbSet<ScoreCard> ScoreCards { get; set; }



   }
}

我的解决方案中还有一个名为QQAForm.Data的项目,它只控制会员资格涉及的所有内容的角色和安全性。 希望这可以帮助。 谢谢你的时间和耐心。

更新于07/06/2012

最终工作编辑:

    [HttpPost]
    public ActionResult Edit(AuditScheduleEdit viewModel)
    {            
        if (ModelState.IsValid)
        {
            viewModel.PopulateCheckBoxsToSpacerType();
            _db.Entry(viewModel.AuditScheduleInstance).State = System.Data.EntityState.Modified;
            _db.SaveChanges();
            return RedirectToAction("Index");
        }
        else
        {
            return View(viewModel);
        }

    }

2012年8月2日更新

我已经决定我可以在这个项目的其他方面使用它。我有多个地方使用复选框。

我试图在另一个视图上实现它,但它无法正常工作。它不起作用的原因是因为为了填充复选框,它会查看当前表中的ID,以便它可以更新它。这是片段:

        //get
    public ActionResult _Forms(int id)
    {
        AuditFormEdit viewModel = new AuditFormEdit();
        viewModel.ScoreInstance = _db.MainAnswers.Single(r => r.MainAnswerID == id);
        viewModel.InitializeScoreCheckBoxHelperList(_db.Scores.ToList());
        return View(viewModel);
    }

    //post
    [HttpPost]
    public ActionResult _Forms(int id, AuditFormEdit viewModel)
    {
        if (ModelState.IsValid)
        {
            viewModel.PopulateCheckBoxsToScores();
            _db.Entry(viewModel.ScoreInstance).State = System.Data.EntityState.Modified;
            _db.SaveChanges();
            return RedirectToAction("/");
        }
        else
        {
            return View(viewModel);
        }
    }

(r =&gt; r.MainAnswerID == id)是问题。 MainAnswer是需要更新的表。该记录还应插入AuditScheduleID,MainQuestionID和从Score复选框填充的文本。如果我发表评论,我什么都得不到。我真正需要的是采取这种方式并插入数据的新记录。 不知道如何更改代码来执行此操作。

2 个答案:

答案 0 :(得分:1)

如果我理解正确,你说:

  1. 客户有一个名为 ProductType string属性,其中包含逗号分隔的 ProductType 名称字符串。
  2. ProductType 具有string属性 ProductName
  3. 在视图中, ProductType 中的任何一个都显示为复选框,可以为每个客户选择/取消选择。
  4. 正确?它对我来说似乎是一种多对多关系

    您是否已阅读MVC教程的这一章:Getting Started with EF using MVC?特别是这部分:Creating a More Complex Data Model for an ASP.NET MVC Application

    如果您将Customer.ProductType的类型从string更改为List<ProductType>,则可以解决所有问题。

    但是,将Customer.ProductType保留为string,仍然可以解决。

    <强>代码

    根据AuditScheduleSpacerProduct类(模型),我开发了一个新的VeiwModel类。将ViewModel视为一个容器,它包含其他类并使它们可以发送到View。

    namespace MvcApplication1.ViewModels
    {
        public class AuditScheduleEdit
        {
            public Models.AuditSchedule AuditScheduleInstance { get; set; }
    
            public List<SpacerProductCheckBoxHelper> SpacerProductCheckBoxHelperList { get; set; }
    
            public void InitializeSpacerProductCheckBoxHelperList(List<Models.SpacerProduct> SpacerProductList)
            {
                if (this.SpacerProductCheckBoxHelperList == null)
                    this.SpacerProductCheckBoxHelperList = new List<SpacerProductCheckBoxHelper>();
    
                if (SpacerProductList != null
                    && this.AuditScheduleInstance != null)
                {
                    this.SpacerProductCheckBoxHelperList.Clear();
                    SpacerProductCheckBoxHelper spacerProductCheckBoxHelper;
                    string spacerTypes =
                        string.IsNullOrEmpty(this.AuditScheduleInstance.spacer_type) ?
                        string.Empty : this.AuditScheduleInstance.spacer_type;
                    foreach (Models.SpacerProduct spacerProduct in SpacerProductList)
                    {
                        spacerProductCheckBoxHelper = new SpacerProductCheckBoxHelper(spacerProduct);
                        if (spacerTypes.Contains(spacerProduct.SpacerName))
                            spacerProductCheckBoxHelper.Checked = true;
                        this.SpacerProductCheckBoxHelperList.Add(spacerProductCheckBoxHelper);
                    }
                }
            }
    
            public void PopulateCheckBoxsToSpacerType()
            {
                this.AuditScheduleInstance.spacer_type = string.Empty;
                var spacerTypes = this.SpacerProductCheckBoxHelperList.Where(x => x.Checked)
                                      .Select<SpacerProductCheckBoxHelper, string>(x => x.SpacerName)
                                      .AsEnumerable();
                this.AuditScheduleInstance.spacer_type = string.Join(", ", spacerTypes);
            }
    
            public class SpacerProductCheckBoxHelper : Models.SpacerProduct
            {
                public bool Checked { get; set; }
    
                public SpacerProductCheckBoxHelper() : base() { }
    
                public SpacerProductCheckBoxHelper(Models.SpacerProduct spacerProduct)
                {
                    this.SpacerProductID = spacerProduct.SpacerProductID;
                    this.SpacerName = spacerProduct.SpacerName;
                    this.SpacerBrand = spacerProduct.SpacerBrand;
                }
            }
        }
    }
    

    所以这里是相关控制器的编辑方法:

        public ActionResult Edit(int id)
        {
            AuditScheduleEdit viewModel = new AuditScheduleEdit();
            viewModel.AuditScheduleInstance = _db.GetAuditScheduleById(id);
            viewModel.InitializeSpacerProductCheckBoxHelperList(_db.GetAvailableSpacerProducts());
            return View(viewModel);
        }
    
        [HttpPost]
        public ActionResult Edit(AuditScheduleEdit viewModel)
        {
            if(ModelState.IsValid)
            {
                viewModel.PopulateCheckBoxsToSpacerType();
                // TODO: Add update logic here
                return RedirectToAction("Index");
            }
            else
            {
                return View(viewModel);
            }
        }
    

    在第一个Action(HttpGET)中,我只是构造一个AuditScheduleEdit的实例,然后从我的数据库(AuditSchedule)分配请求的_db.GetAuditScheduleById(id)(您可能有不同的方式来查询数据来自您的存储库)。

    然后必须将SpacerProducts的集合传递给InitializeSpacerProductCheckBoxHelperList()函数(抱歉,因为长名称,试图清楚易懂!)。此函数创建一个SpacerProductCheckBoxHelper列表,用于在视图上生成复选框。

    当用户提交表单时,将重新创建AuditScheduleEdit(基于表单数据),并将其发送到第二个编辑操作(HttpPost)。在那里,PopulateCheckBoxsToSpacerType()将选中的复选框列表转换为以逗号分隔的字符串,并将其分配给AuditSchedule.spacer_type

    这是视图:

    @model MvcApplication1.ViewModels.AuditScheduleEdit
    @using (Html.BeginForm())
    {
        <div>
            <h3>Audi Schedule</h3>
            @Html.LabelFor(m => m.AuditScheduleInstance.AuditScheduleID)
            @Html.DisplayFor(m => m.AuditScheduleInstance.AuditScheduleID)
            @Html.HiddenFor(m => m.AuditScheduleInstance.AuditScheduleID)
            <br />
            @Html.LabelFor(m => m.AuditScheduleInstance.Control_ID)
            @Html.EditorFor(m => m.AuditScheduleInstance.Control_ID)
            // Here, add any field of AuditSchedule which needs to show on edit form 
            //       like what I did for AuditScheduleID and Control_ID.
            <h3>SpacerType</h3>
            @for (int index = 0; index < Model.SpacerProductCheckBoxHelperList.Count; index++)
            {
                @Html.CheckBoxFor(m => m.SpacerProductCheckBoxHelperList[index].Checked)
                @Html.LabelFor(m => m.SpacerProductCheckBoxHelperList[index], Model.SpacerProductCheckBoxHelperList[index].SpacerName)
                @Html.HiddenFor(m => m.SpacerProductCheckBoxHelperList[index].SpacerProductID)
                @Html.HiddenFor(m => m.SpacerProductCheckBoxHelperList[index].SpacerName)
                <br />
            }
        </div>
        <div>
            <input type="submit" value="Save" />
        </div>
    }
    

    我在Visual Studio developer 2010 Exp中编写了这段代码,效果很好。 You can download this code from here

答案 1 :(得分:0)

我不清楚您提出的问题,但我认为您需要更新 当复选框值存储在您创建的表中时,您在表(View)中的记录。我认为不需要更新您的表,您只需要创建一个关系 在两个表之间,然后你可以在内部查询和连接的帮助下获得所有日期。

但是如果你需要更新你的表,你可以在你创建的表中使用“插入后”触发器。 如果您也可以共享表结构,那将非常有用。

您需要再创建一个表(存储itemselected与选择它的客户的关系) 使用列(AuditScheduleID int,SpacerType int),此表应在两个列上都有复合键 和 1)列AuditScheduleID应与Customer表具有外键关系 2)列SpacerType与Product表具有外键关系。 3)当客户选择多个产品并提交每个产品的信息时。 AuditScheduleID 应该保存为上面创建的表中的不同行。

现在,您可以使用完全标准化

以这种方式存储数据