JamesStuddart
JamesStuddart

Reputation: 2611

dynamically add EditorTemplates to current page, on dropdown change

I currently have a 3 step wizard.

Step 1: takes some details I need and has a dropdown where you select the number of packages

Step 2: depending on how many packages you selected this step shows you the required number of editors for packages

Step 3: confirm your order

I have been told I need to combine steps 1 & 2 but I am at a loss on how to do this with mvc and razor, because its simply a VIEW on your model...

What is the best way to do this?

would it be a case of submitting the page back to itself with an action dedicated specifying how many packages are required, or could this be done with ajax?

Thanks

Upvotes: 2

Views: 653

Answers (1)

Nick
Nick

Reputation: 5892

My approach would be as follows:

Create a partial for the package row (PackageRow.cshtml)

@model IEnumerable<PackageViewModel>
<div class="editorRow">
@using (Html.BeginCollectionItem("packages"))
{
    @Html.TextBoxFor(x => x.WhateverYouNeed) 
}
</div>

Load your package rows into the form via ajax upon the user selecting the number of rows

@Html.ActionLink("Go!", "AddPackages", null, new { id = "addPackages" })

<div id="editorRows"></div>

<script type="text/javascript">
$(document).ready(function () {
        $("#addPackages").click(function () {
            $.ajax({ url: this.href, cache: false, success: function (html) {
                $("#editorRows").append(html); // add the number of rows you need here
            }
            }); return false;
        });
        $("a.deleteRow").live("click", function () { $(this).parents("div.editorRow:first").remove(); return false; });
    });  
</script>   

Add your partials to the form via your controller

public ActionResult AddPackages()
{
    return PartialView("PackageRow", new PackageViewModel { ... });
}

Save the data

 [Authorize]
 [HttpPost]
        public ActionResult CreatePackages(int id, FormCollection fc)
        {

            int nrKeys = fc.AllKeys.Count();
            int i = 0;

            int interations = (nrKeys / 2);

            foreach (var key in fc.AllKeys)
            {

                if (nrKeys <= i)
                    break;

                if (i != 0)
                {
                    string value1 = fc[i];
                    string value2 = fc[i + 1];
                   ...
                }
                else
                {
                    i++;
                }

           ...

Upvotes: 2

Related Questions