MVC 3 Dynamic Form Using a ViewModel

前端 未结 1 1022
感动是毒
感动是毒 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 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
    
    
    
    
    
    @using (Html.BeginForm())
    {
        @Html.ValidationSummary(true)
    
        
    @Html.LabelFor(model => model.Recipe.RecipeName) @Html.EditorFor(model => model.Recipe.RecipeName) @Html.ValidationMessageFor(model => model.Recipe.RecipeName)
    RecipeIngredients
    @Html.EditorFor(model => model.RecipeIngredients)
    }

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

    @model RecipeIngredient
    
    @using (Html.BeginCollectionItem("RecipeIngredients"))
    {
        
    @Html.LabelFor(model => model.Amount) @Html.EditorFor(model => model.Amount) @Html.ValidationMessageFor(model => model.Amount)
    @Html.LabelFor(model => model.IngredientDesc) @Html.EditorFor(model => model.IngredientDesc) @Html.ValidationMessageFor(model => model.IngredientDesc)
    }

    0 讨论(0)
提交回复
热议问题