Utilizing Html.BeginCollectionItem helper to pass a collection with only a glimpse of the whole picture

After seeking guidance from Stephen Muecke on a small project, I have encountered an issue. The javascript successfully adds new fields from the Partial View and connects them to the model through "temp" values set by the controller method for the partial view.

However, upon submitting the new fields, the AddRecord() method throws an exception indicating that the model is not being passed in ("Object reference not set to an instance of an object").

Additionally, inspecting the page source reveals that the BeginCollectionItem helper is placing a hidden tag around the table in the main view displaying existing records, but not around the new fields added via javascript.

Could someone please point out what mistake I may be making? As a beginner in this field, I appreciate your patience!

Here is my main view:

@model IEnumerable<DynamicForm.Models.CashRecipient>

@using (Html.BeginForm("AddDetail", "CashRecipients", FormMethod.Post))
{
    @Html.AntiForgeryToken()
    <div id="CSQGroup">
    </div>
}

<div>
    <input type="button" value="Add Field" id="addField" onclick="addFieldss()" />
</div>

<script>
    function addFieldss()
    {   
        //alert("ajax call");
        $.ajax({
            url: '@Url.Content("~/CashRecipients/RecipientForm")',
            type: 'GET',
            success:function(result) {
                //alert("Success");
                var newDiv = document.createElement("div"); 
                var newContent = document.createTextNode("Hi there and greetings!"); 
                newDiv.appendChild(newContent);  
                newDiv.innerHTML = result;
                var currentDiv = document.getElementById("div1");  
                document.getElementById("CSQGroup").appendChild(newDiv);
            },
            error: function(result) {
                alert("Failure");
            }
        });
    }
</script>

This is my Partial View:

@model DynamicForm.Models.CashRecipient
@using HtmlHelpers.BeginCollectionItem

@using (Html.BeginCollectionItem("recipients"))
{
    <div class="editor-field">
        @Html.LabelFor(model => model.Id)
        @Html.LabelFor(model => model.cashAmount)
        @Html.TextBoxFor(model => model.cashAmount)
        @Html.LabelFor(model => model.recipientName)
        @Html.TextBoxFor(model => model.recipientName)
    </div>
    <div class="form-group">
        <div class="col-md-offset-2 col-md-10">
            <input type="submit" value="Save" class="btn btn-default" />
        </div>
    </div>
}

And here is my model:

public class CashRecipient
{
    public int Id { get; set; }
    public string cashAmount { get; set; }
    public string recipientName { get; set; }  
}

The code snippet from my controller is as follows:

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult AddDetail([Bind(Include = "Id,cashAmount,recpientName")] IEnumerable<CashRecipient> cashRecipient)
{
    if (ModelState.IsValid)
    {
        foreach (CashRecipient p in cashRecipient) {
            db.CashRecipients.Add(p);
        }
        db.SaveChanges();
        return RedirectToAction("Index");

    }

    return View(cashRecipient);
}

public ActionResult RecipientForm()
{
    var data = new CashRecipient();
    data.cashAmount = "temp";
    data.recipientName = "temp";
    return PartialView(data);
}

Answer №1

To begin, start by constructing a view model that will represent the data you want to modify. In this case, let's assume that cashAmount is a monetary value and should therefore be a decimal type (you can also include other validation and display attributes as needed).

public class CashRecipientVM
{
    public int? ID { get; set; }
    public decimal Amount { get; set; }
    [Required(ErrorMessage = "Please enter the name of the recipient")]
    public string Recipient { get; set; }  
}

Next, create a partial view named _Recipient.cshtml

@model CashRecipientVM
<div class="recipient">
    @using (Html.BeginCollectionItem("recipients"))
    {
        @Html.HiddenFor(m => m.ID, new { @class="id" })
        @Html.LabelFor(m => m.Recipient)
        @Html.TextBoxFor(m => m.Recipient)
        @Html.ValidationMesssageFor(m => m.Recipient)
        @Html.LabelFor(m => m.Amount)
        @Html.TextBoxFor(m => m.Amount)
        @Html.ValidationMesssageFor(m => m.Amount)
        <button type="button" class="delete">Delete</button>
    }
</div>

Additionally, implement a method to return this partial view:

public PartialViewResult Recipient()
{
    return PartialView("_Recipient", new CashRecipientVM());
}

Your main GET method should look like this:

public ActionResult Create()
{
    List<CashRecipientVM> model = new List<CashRecipientVM>();
    .... // add any existing objects that your editing
    return View(model);
}

This method's corresponding view will be:

@model IEnumerable<CashRecipientVM>
@using (Html.BeginForm())
{
    <div id="recipients">
        foreach(var recipient in Model)
        {
            @Html.Partial("_Recipient", recipient)
        }
    </div>
    <button id="add" type="button">Add</button>
    <input type="submit" value="Save" />
}

Include a script that adds HTML for a new CashRecipientVM:

var url = '@Url.Action("Recipient")';
var form = $('form');
var recipients = $('#recipients');
$('#add').click(function() {
    $.get(url, function(response) {
        recipients.append(response);
        form.data('validator', null);
        $.validator.unobtrusive.parse(form);
    });
});

Lastly, here's the script to delete an item:

$('.delete').click(function() {
    var container = $(this).closest('.recipient');
    var id = container.find('.id').val();
    if (id) {
        $.post(yourDeleteUrl, { id: id }, function(result) {
            container.remove();
        }.fail(function (result) {
            // Display error message if something went wrong
        });
    } else {
        container.remove();
    }
});

The form will submit back to:

public ActionResult Create(IEnumerable<CashRecipientVM> recipients)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

When you scroll through the page, white blocks suddenly appear

After completing a website, I noticed some white blocks appearing when scrolling. You can view the site here. This issue occurs on both mobile and desktop devices during the initial load only. Could this indicate that the page has not fully loaded yet? If ...

Unexpected value detected in D3 for translate function, refusing to accept variable

I'm experiencing a peculiar issue with D3 where it refuses to accept my JSON data when referenced by a variable, but oddly enough, if I print the data to the console and manually paste it back into the same variable, it works perfectly fine. The foll ...

Updating HTML content based on an active user session using Node.js/Express - A Step-by-Step Guide

I'm struggling to find a way to remove the login/signup buttons once a user has successfully logged in. The issue lies within my header file that needs some modification. <section class="header"> <div class="wrapper"> <nav ...

Switching the visibility of multiple textareas from block to none

I am currently exploring ways to make one text area disappear while another one appears in its place. With limited knowledge of Javascript and just starting my journey into HTML and CSS, I am reaching out to the forum for assistance or guidance on the rig ...

Tips on placing an li element into a designated DIV

Just starting out with jquery and working on a slider project. Here's what I have so far: <ul> <li> <img src="image.jpg"><p>description of the current image</p></li> <li> <img src="image.jpg"> ...

Transforming Form Input into Request Payload for an AJAX Call

I'm facing a challenge in submitting my form data through a POST AJAX request and haven't been able to come across any solutions so far. Due to the dynamic creation of the form based on database content, I can't simply fetch the values usin ...

Tips for creating a seamless horizontal scrolling effect in Angular when hovering (automatically)

One of the components I'm working on features a gallery with an X axis orientation. <div class="gallery"> <div (mouseenter)="scrollTo('left', $event)" (mouseleave)="clearIntervalRepeater()" class="left"></div> < ...

Tips on successfully transferring row data that has been clicked or selected from one adjacent table to another table

Currently, I am facing a challenge with two tables that are positioned next to each other. My goal is to append a selected row from the first table to the second table. After successfully extracting data from the selected row and converting it into an arr ...

Show informational pop-up when hovering over selected option

My goal is to create an information box that appears when a user hovers over a select option. For example: <select id = "sel"> <option value="sick leave">Sick leave</option> <option value="urgent leave">Urgent lea ...

Utilize JSX to dynamically insert HTML tags onto a webpage

I am trying to achieve a specific task in JSX, where I want to identify all strings enclosed within delimiters :; and wrap them with HTML Mark tags to highlight them. However, the current implementation is not rendering the tags as expected. Is there a sol ...

Differences in characteristics of Javascript and Python

As I tackle an exam question involving the calculation of delta for put and call options using the Black and Scholes formula, I stumbled upon a helpful website . Upon inspecting their code, I discovered this specific function: getDelta: function(spot, str ...

Implementing multiple modules within a shared parent route in Angular

Currently, I am seeking a method to load multiple modules under the same path in Angular. Let's say I have three modules: AModule, BModule, and CModule, each with its own RouterModule.forChild call. My goal is to combine these modules under the route ...

Navigate to a local server running on localhost:3000 and access the external URL www.google.com

When attempting to access an external URL, the website that should open in a new tab is redirecting to http://localhost:3001/www.google.com instead of www.google.com. <IconButton key={index} size="large" color="primary" href={e.url ...

Show the components only if the final digit in their identification number is less than i

I have several span elements with IDs like "tag1", "tag2", etc. I want to display only the spans whose ID ends with a number less than 19. These elements are part of a class called "notVis", which is hidden by default using $(".notVis").hide(); when the ...

Building web navigation using a combination of HTML, JavaScript, and PHP within a category, sub

I've been struggling to find a detailed tutorial on implementing a dynamic website navigation system using javascript or php. It seems like every time I attempt to research this topic, I end up feeling confused and unsure of where to start. My goal i ...

What are some ways to ensure that a webpage has been actively viewed for a minimum of X seconds?

In my project, users have the opportunity to earn a bonus by viewing specific pages. When they visit the bonus selection site, an iframe displays the page along with a countdown timer. Once the countdown reaches zero, they can then click the "Get Reward" b ...

To enhance user experience, it is recommended to reload the page once

Hello, I'm looking for a way to automatically refresh the page after submitting an AJAX form. Currently, I have an onClick function that seems to refresh the page, but I still need to press F5 to see the changes I've made. Here's the JavaSc ...

Changing the background color of .pane and .view elements in an Ionic web application using JavaScript

Looking to modify the background-color of two css selectors, .pane and .view, that are located within the ionic.css file. Despite multiple attempts to do so using JavaScript directly in the index.html file, the changes are not reflected. The code snippet ...

Using jQuery to access a server-side SQL database through PHP

After searching for an example on connecting a client to a server's SQL database using JQuery, AJAX, and PHP, I came across this seemingly well-executed guide: Example Link. All my PHP files and the jQuery library (javascript-1.10.2.min.js) are contai ...

Tips for showing more rows by clicking an icon within an Angular 2 table

When I click on the plus (+) button in the first column of each row, only one row expands. How can I modify it to expand multiple rows at a time? Thanks in advance. <div> <table class="table table-striped table-bordered"> <thead> ...