简体   繁体   中英

How do I create a form in asp.net MVC 5

I'm used to web forms, but am switching to MVC 5 and have a question about creating a multi step application form.

This form is like a wizard then will display information entered in each step at the end, then submit.

Is it easier to write this using html form in the .cshtml or do it all in the controller?

THank you

MVC, as its name suggests, has a Model, a View, and Controller. To create a form, you set up a class that will act as your Model, containing the properties that need to be worked with in a particular view. This is a different thing than your entity , the class that corresponds to a table in your database. You can sometimes use the entity as the Model, but especially in the case of a multi-step form, you don't want to persist the data until the end, which means, they'll need to be separate.

This brings us to the topic of view models , which is actually from another different pattern called MVVM. Regardless, your Model for these views will be a series of view models that contain just the information that the particular step needs to collect. At the end, you will piece all of the collected data together by creating an instance of your entity and mapping the property values from each view model over to it. Then, you will save the entity.

Now, as far as persisting the collected data between requests goes, that's where your session comes in. You'll merely add each posted view model into your Session object, and then at the end, fetch all of them from the Session object to create your entity.

So each POST action will have something like the following:

[HttpPost]
public ActionResult Step1(Step1ViewModel model)
{
    if (ModelState.IsValid)
    {
        Session["Step1"] = model;
        return RedirectToAction("Step2");
    }

    // errors
    return View(model);
}

Then, your final POST action:

[HttpPost]
public ActionResult StepFinal(StepFinalViewModel)
{
    if (ModelState.IsValid)
    {
        var myEntity = new MyEntity();

        var step1 = Session['Step1'] as Step1ViewModel;
        myEntity.SomeField = step1.SomeField;
        // ... repeat for field in view model, then for each step


        db.MyEntities.Add(myEntity);
        db.SaveChanges();

        Session.Remove('Step1');
        // repeat for each step in session

        return RedirectToAction("Success");
    }

    // errors
    return View(model);
}

All of your form information will be in the .cshtml file like this:

@using (Html.BeginForm("Controller Action Method", "Controller Name", FormMethod.Post, new { id = "Form Name" }))
{
// Form Elements here
}

Then you can simply add a submit button that submits the form to your Controller for processing.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM