Add dynamic form content to MVC

I am trying to add dynamic content to my mvc application.

I am using Steven Sanderson's post Editing a variable length list, ASP.NET MVC 2-style , and thanks to this I have some dynamic content in it. Due to some limitations of my application, I had to make changes to the Base Gift class.

The problem is that now the application is not working.

In my model, I have:

public class Gift { //public string Name { get; set; } //public double Price { get; set; } public List<string> MyList { get; set; } } 

And now, I get zero values ​​in the gifts parameter

 [HttpPost] public ActionResult Index(IEnumerable<Gift> gifts) { return View("Completed", gifts); } 

Can someone help me with this?

EDIT: Here is my view code:

 <%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<IEnumerable<Enviro2011.Models.Gift>>" %> <asp:Content ContentPlaceHolderID="HeadContent" runat="server"> <link rel="Stylesheet" href="../../Content/styles.css" /> <script type="text/javascript"> $(document).ready(function () { $("#addItem").click(function () { $.ajax({ url: this.href, cache: false, success: function (html) { $("#editorRows").append(html); } }); return false; }); $("a.deleteRow").live("click", function () { $(this).parents("div.editorRow:first").remove(); return false; }); }); </script> </asp:Content> <asp:Content ContentPlaceHolderID="MainContent" runat="server"> <h2> Gift List</h2> What do you want for your birthday? <% using (Html.BeginForm()) { %> <div id="editorRows"> <% foreach (var item in Model) Html.RenderPartial("GiftEditorRow", item); %> </div> <%: Html.ActionLink("Add another...", "Add", null, new { id = "addItem" }) %> <input type="submit" value="Finished" /> <% } %> </asp:Content> 

Edit2 I also found the message “Binding To A List” from Phil Haack and works fine, but I can’t implement the Add Book function !!!

+4
source share
2 answers

The problem is that you are viewing the model, not the elements in the model.

Here is what you can do:

 <% foreach (var item in Model.MyList) // <-- Add the ".MyList" Html.RenderPartial("GiftEditorRow", item); %> 

Suppose your partial view gets only a string.

Since your Ajax call does not work, the problem is that you are trying to send twice, once using actionLink and the other using Ajax. Change ActionLink to an explicit link without any action behind it:

 <a id="addItem">Add another ...</a> 

Then your jQuery Ajax call will be launched.

+5
source

You have the action below in your controller

public ActionResult Add ()
{
return View ("GiftEditorRow", new MyList ());
}

0
source

Source: https://habr.com/ru/post/1332705/


All Articles