[EDITED] my previous question closed as duplicate, but I don't think so and I write why below. If I'm wrong, please leave a couple words of explanations if you decide to do it again. I'm newbie in dev, but I read a bunch of SO questions about topic which already been asked and still don't find answer
My goal is to create a form with input fields that can be added from View by clicking on button. I don't know how many fields a user want to add and also I need that form will be bound to List < MyModel > and when user send it'll return to action List < MyModel >.
I created sample project to show you my solution which doesn't work. Can you help me with it please?
MyModel
public class MyDogModel { public string Name { get; set; } public string Breed { get; set; } }
Controller
public class HomeController : Controller { public ActionResult Index() { Session.Clear(); return View(); } [HttpPost] public ViewResult MyDogs (List<MyDogModel> myDogs) { return View(myDogs); } [HttpPost] public PartialViewResult AddDog(List<MyDogModel> dogs) { int fieldsCount; if (Session["FieldsCount"] == null) { Session["FieldsCount"] = 1; fieldsCount = 1; } else { fieldsCount = (int)Session["FieldsCount"]; Session["FieldsCount"] = fieldsCount++; } return PartialView(dogs); } }
Index
@{ AjaxOptions options = new AjaxOptions { HttpMethod = "post", UpdateTargetId = "MyDogsForm", InsertionMode = InsertionMode.Replace }; Layout = null; } <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width" /> <title>Index</title> <script src="~/Scripts/jquery-1.8.0.js"></script> <script src="~/Scripts/jquery.unobtrusive-ajax.js"></script> </head> <body> <div> @Ajax.ActionLink("Add new dog", "AddDog", options) <div if="MyDogsForm"> </div> </div> </body> </html>
Here in AddDog View I'm getting null reference error in this string
@Html.TextBoxFor(d => d[i].Breed); Exception thrown: 'System.NullReferenceException' in System.Web.Mvc.dll
@model List<WebApplication2.Models.MyDogModel>
@using (@Html.BeginForm("MyDogs","Home"))
{
for (int i = 0; i < (int)Session["FieldsCount"]; i++)
{
@Html.TextBoxFor(d => d[i].Name);
@Html.TextBoxFor(d => d[i].Breed);
}
<button type="submit">Send</button>
}
What does it mean? I just want to fill my List with number of dogs which user'll want to add.
EDIT Thanks @stephen-muecke for suggested solution. Maybe I'm missing something. But actually I'm looking for solution, where form will created and fulfilled with some data at the server. In this answer POST a form array without successful new fields added by JQuery, I'll try it if server-side form changes via ajax not possible, but it'll be more convenient for me to avoid JQuery cause I need to bind not just TextBoxes, but DropDownLists and so on with information which generated on server from database.