1

I am a newbie to MVC3 technology and trying to workout my way get through a small problem. I simply need to get checked checkbox values to be saved in database and on Edit view check them back.

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

When the Submit button is clicked, the [HTTPPOST] Action method of the desired controller is called. There I receive the selected values in this form :

 var selectedCheckBoxValues = Request.Form["DocSub"];

I am getting the all the checked checkbox values in comma separated form and able to store them to the database, but wondering if this is the right approach to go by.

Also I need to know to retrieve checkbox values from database on Edit view in already checked form.

1
  • let me know if you have any remaining questions, if my answer has fully answered your questions, please mark it accordingly Commented Jun 17, 2013 at 0:38

1 Answer 1

2

the typical apporoach to these problems is to use a view with a model

ie, suppose this is 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 )

and use a viewmodel to pass data to the view

the viewmodel is a class where you have the data your going to send to the view, ie.

public class DocumentViewModel{
     public bool Photo {get;set;}
     public bool BirthCertificate { get; set; }
     public bool SchoolLeavingCertificate {get;set;}
}

and you'd have a controller that populates the viewmodel and calls the view

    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);
    }

look for tutorials out there on mvc basics. read code.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.