0

[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?

  1. MyModel

    public class MyDogModel
    {
       public string Name { get; set; }
       public string Breed { get; set; }
    }
    
  2. 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);
        }
    }       
    
  3. 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>
    
  4. 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.

Community
  • 1
  • 1
PilgrimViis
  • 1,511
  • 2
  • 17
  • 21
  • 1
    you added the count of the dogs but your list is empty – Monah Sep 18 '16 at 20:52
  • 1
    why you don't ask the user about how many dogs wants to add, and you pass it to the AddDogs(int numberOfDogs), and inside this function create a List of dogs and add number of dogs entries to the list and posted to the client again and it will work, shall I provide sample for you? – Monah Sep 18 '16 at 20:55
  • 1
    It makes no difference if its dropdownlists or textboxes. Ajax uses javascript do saying you want to avoid javascript/jquery makes no sense and using a link (your `Ajax.ActionLink()`) makes no sense either. If you want to add and save one 'Dog' at a time, then you need a modal form in your view that uses ajax to submit the form (something along the lines of [this fiddle](http://jsfiddle.net/9madrh7g/2/)) but that means your current POST method makes no sense –  Sep 18 '16 at 22:48
  • @HadiHassan, but it should be, isn't it? I want the user to fill the list and send it on server. Sessin["fieldsCount"] used to count how many times user create a new inputs for new dog. About "ask home many"... I think it's more information that I needed. Cause I can obtain it from counts of click "add new dog button" – PilgrimViis Sep 19 '16 at 10:27
  • @StephenMuecke , so as I got it right. It's not possible to create a partial view that would be dynamically replaced with same partial view, but with more input fields, each time when user click on button without jquery, using just Unobtrusive Ajax (yes I know technically it's created javascript and so on)? I created a simple gif with how it's gonna work. But I'm used TextBox and string arrays, not TextBoxFor. http://imgur.com/a/elGIT – PilgrimViis Sep 19 '16 at 10:34
  • P.S. thanks for the http://jsfiddle.net/9madrh7g/2/ – PilgrimViis Sep 19 '16 at 10:40
  • 1
    Sorry, not sure what your saying. And why do you want to use the obsolete `Ajax` methods anyway (its not even supported in the latest MVC). But I already gave you [a link to my answer](http://stackoverflow.com/questions/28019793/submit-same-partial-view-called-multiple-times-data-to-controller/28081308#28081308) in your previous question that uses the `BeginCollectionItem` helper to generate a partial view which you can call using `Ajax.ActionLink()` –  Sep 19 '16 at 10:40
  • @StephenMuecke, okay I'll trust you and try to do it your way. Maybe I just don't understand your idea completely for this moment. – PilgrimViis Sep 19 '16 at 10:45

0 Answers0