MVC 3 Dynamic Form Using a ViewModel

前端 未结 1 1014
感动是毒
感动是毒 2020-12-14 05:03

I have been trying for weeks to follow a couple tutorials on how to create a dynamic form giving the ability to add another \"ingredient\" to the form. Here is the article I

相关标签:
1条回答
  • 2020-12-14 05:47

    There are lots of issues with your code. I prefer to go step by step in order to illustrate a simplified example that you could adapt to your needs.

    Models:

    public class RecipeViewModel
    {
        public Recipe Recipe { get; set; }
        public IList<RecipeIngredient> RecipeIngredients { get; set; }
    }
    
    public class Recipe
    {
        public string RecipeName { get; set; }
    }
    
    public class RecipeIngredient
    {
        public int Amount { get; set; }
    
        [Required]
        public string IngredientDesc { get; set; }
    }
    

    Controller:

    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            var recipeViewModel = new RecipeViewModel();
            return View(recipeViewModel);
        }
    
        [HttpPost]
        public ActionResult Index(RecipeViewModel recipeViewModel)
        {
            if (!ModelState.IsValid)
            {
                // there wre validation errors => redisplay the view
                return View(recipeViewModel);
            }
    
            // TODO: the model is valid => you could pass it to your 
            // service layer for processing
    
            return RedirectToAction("Index");
        }
    
        public ActionResult GetNewRecipeIngredient()
        {
            return PartialView("~/Views/Shared/EditorTemplates/RecipeIngredient.cshtml", new RecipeIngredient());
        }
    }
    

    View (~/Views/Home/Index.cshtml):

    @model RecipeViewModel
    
    <script src="@Url.Content("~/Scripts/jquery.validate.js")" type="text/javascript"></script>
    <script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.js")" type="text/javascript"></script>
    <script type="text/javascript">
        $(function() {
            $('#add-recipeingredient').click(function () {
                $.ajax({
                    url: '@Url.Action("GetNewRecipeIngredient")',
                    type: 'POST',
                    success: function (data) {
                        $('.new-recipeingredients').append(data);
                    }
                });
                return false;
            });
        });
    </script>
    
    @using (Html.BeginForm())
    {
        @Html.ValidationSummary(true)
    
        <div>
            @Html.LabelFor(model => model.Recipe.RecipeName)
            @Html.EditorFor(model => model.Recipe.RecipeName)
            @Html.ValidationMessageFor(model => model.Recipe.RecipeName)
        </div>
    
        <fieldset>
            <legend>RecipeIngredients</legend>
            <div class="new-recipeingredients">
                @Html.EditorFor(model => model.RecipeIngredients)
            </div>
            <div style="padding: 10px 0px 10px 0px">
                <a id="add-recipeingredient" href="javascript:void(0);">Add another</a>
            </div>
        </fieldset>
    
        <div>
            <input type="submit" value="CreateFullRecipe" />
        </div>
    }
    

    Editor template (~/Views/Shared/EditorTemplates/RecipeIngredient.cshtml):

    @model RecipeIngredient
    
    @using (Html.BeginCollectionItem("RecipeIngredients"))
    {
        <div>
            @Html.LabelFor(model => model.Amount)
            @Html.EditorFor(model => model.Amount)
            @Html.ValidationMessageFor(model => model.Amount)
        </div>
    
        <div>
            @Html.LabelFor(model => model.IngredientDesc)
            @Html.EditorFor(model => model.IngredientDesc)
            @Html.ValidationMessageFor(model => model.IngredientDesc)
        </div>
    }
    
    0 讨论(0)
提交回复
热议问题