Asp.net mvc 3 保存和检索复选框值asp.net mvc3

Asp.net mvc 3 保存和检索复选框值asp.net mvc3,asp.net-mvc-3,Asp.net Mvc 3,我是MVC3技术的新手,试图通过自己的方式解决一个小问题。 我只需要选中要保存在数据库中的复选框值,然后在编辑视图上重新选中它们 <input type="checkbox" value="Photo" name="DocSub" /> Photograph<br /> <input type="checkbox" value="BirthCertificate" name="DocSub" /> Copy Of Birth Certificate<br

我是MVC3技术的新手,试图通过自己的方式解决一个小问题。 我只需要选中要保存在数据库中的复选框值,然后在编辑视图上重新选中它们

<input type="checkbox" value="Photo" name="DocSub" /> Photograph<br />
<input type="checkbox" value="BirthCertificate" name="DocSub" /> Copy Of Birth Certificate<br />
<input type="checkbox" value="School Leaving Certificate" name="DocSub" /> School Leaving Certificate<br />
我以逗号分隔的形式获取所有复选框值,并能够将它们存储到数据库中,但我想知道这是否是正确的方法


此外,我还需要知道如何从数据库中以已选中的形式从编辑视图中检索复选框值。

解决这些问题的典型方法是使用带有模型的视图

假设这是view Documents.cshtml

@model DocumentViewModel 

@Html.LabelFor(m => m.Photo)
@Html.CheckBoxFor( m => m.Photo )

@Html.LabelFor(m => m.BirthCertificate)
@Html.CheckBoxFor( m => m.BirthCertificate )

@Html.LabelFor(m => m.SchoolLeavingCertificate)
@Html.CheckBoxFor( m => m.SchoolLeavingCertificate )
并使用viewmodel将数据传递给视图

viewmodel是一个类,其中包含要发送到视图的数据,即

public class DocumentViewModel{
     public bool Photo {get;set;}
     public bool BirthCertificate { get; set; }
     public bool SchoolLeavingCertificate {get;set;}
}
您将拥有一个填充viewmodel并调用视图的控制器

    public ActionResult Documents()
    {
        var modelData = new DocumentViewModel(); 
         //or retrieve from database at this point
         // ie. modelData.Photo = some database value
        return View(modelData);
    }

    [HttpPost]
    public ActionResult Documents(DocumentViewModel documentsVM)
    {
        if (ModelState.IsValid)
        {
            //update the database record, save to database... (do stuff with documentsVM and the database)

            return RedirectToAction("NextAction");
        }
         //else, if model is not valid redirect back to the view

        return View(documentsVM);
    }

寻找关于mvc基础知识的教程。阅读代码。

如果您还有任何问题,请告诉我,如果我的答案完全回答了您的问题,请相应地标记
    public ActionResult Documents()
    {
        var modelData = new DocumentViewModel(); 
         //or retrieve from database at this point
         // ie. modelData.Photo = some database value
        return View(modelData);
    }

    [HttpPost]
    public ActionResult Documents(DocumentViewModel documentsVM)
    {
        if (ModelState.IsValid)
        {
            //update the database record, save to database... (do stuff with documentsVM and the database)

            return RedirectToAction("NextAction");
        }
         //else, if model is not valid redirect back to the view

        return View(documentsVM);
    }