Sending data from a partial view to a controller

Imagine I have two models: DailyTasks and Task. The initial view is strongly typed with the DailyTasks model, displaying a list of existing tasks for the day. Users can add more tasks to the list/table by clicking the add button. Upon clicking the add button, a partial view linked to the Task model is rendered.

I aim to save any changes made by the user to the existing tasks as well as newly added tasks.

I am currently exploring different methods such as model binding and creating a JSON object of the model to pass it to the controller upon Save. However, I have encountered an issue where only the existing tasks are passed back to the Save controller, and none of the newly added tasks are included.

Model:

public class DailyTasks
{  
   public int ID { get; set; }
   public List<Task> TaskList{ get; set; }
}

public class Task
{
   public int Id { get; set; }
   public string MyTask { get; set; }
}

Main View:

@model Example.Models.DailyTasks

@using (Ajax.BeginForm("Save", "DailyTasks", new AjaxOptions { HttpMethod = "Post" }))
{
<input type="button" value="Add New Task" id="addBtn" />
<input type="submit" value="Save" id="saveBtn"/>

<table class="table">
    <tr>
        <th>Column Header Name Goes Here</th>
        <th>Column Header Name Goes Here</th>
    </tr>

    @for (var i = 0; i < Model.TaskList.Count(); i++)
    {
    <tr>
        <td>
            @Html.DisplayFor(m => Model.TaskList[i].ID)
            @Html.HiddenFor(m => Model.TaskList[i].ID)
        </td>
        <td>
            @Html.DisplayFor(m => Model.TaskList[i].MyTask)
            @Html.HiddenFor(m => Model.TaskList[i].MyTask)
        </td>
    </tr>
    }
</table>
}

<script type="text/javascript">
$(document).ready(function () {
    $("#addBtn").on("click", function () {
        $.get('@Url.Action("AddTask")', function (data) {
            $("table tbody").append(data);
        });
    });
 });
</script>

Add New Task ActionResult for Partial View:

public ActionResult AddTask()
    {
        Task model = new Task();
        return PartialView("_AddTask", model);
    }

Partial View (_AddTask):

    @model Example.Models.Task

    <tr>
        <td>
            @Html.DisplayFor(m => Model.ID)
            @Html.HiddenFor(m => Model.ID)
        </td>
        <td>
            @Html.DisplayFor(m => Model.MyTask)
            @Html.HiddenFor(m => Model.MyTask)
        </td>
    </tr>

Answer №1

This website provided me with the perfect solution I was looking for: . Now, instead of using FormCollection and Request, I can utilize modelbinding method which is much more efficient.

I really hope this information can benefit others in the future. Special thanks to Tobias for sharing this link. It addressed the main issue I was facing, although the solution didn't quite work out for me.

Cheers to progress!

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

Why am I receiving undefined for req.user in passportjs?

After setting up passportJS with my node express app, I encountered an issue where the req.user is undefined when making a login/register request. I am not sure what went wrong or if I missed something in the configuration of passport js. In my setup, I us ...

Increasing Taxes and Boosting the Overall Cost

How can we set up a system where taxes are bypassed by default unless otherwise specified when placing an order? Let's take a look at the following text box: <input class="txt1" type="text" name="subtotal" value="" id="subtotal" size="16" ta ...

Tips for verifying the presence of a Firestore Document reference within a JavaScript array of Document references

I am currently dealing with a document that contains an array field storing references to other documents. Upon fetching the document data and verifying if a document reference exists within the array, I consistently receive a result indicating that it is ...

Does Postgres have a similar feature to SQL Server's Open from rowset command that allows importing JSON files?

We are currently transferring code from a SQL Server database to a Postgres v16 database There is a sample file named 'temprj.json' with the following structure: temprj.json { "ChannelReadings": [ { "ReadingsDto": [ ...

Guide on how to separate the nested JSON by utilizing a Jolt specification within Apache Nifi

Looking to create a specifications document for a new project. Can anyone offer some guidance? Here is the input data: { "VulnId": 90089, "source": "WERUA", "sourceId": "WERT38173", "StateDesc ...

The input fields within the puzzle grid must be synchronized with the values in the list

I'm brand new to JQuery and I'm currently working on a project where I need to update input boxes using a JQuery callback. I'm developing a puzzle grid, with each grid cell being an input box. My goal is to have users type English letters in ...

What methods can be used to create a universal JS function for popup windows?

How can I create a more flexible code structure? I have successfully implemented the functionality using the following approach: let popup1 = document.getElementById("popup-1"); function openPopup1() { popup1.classList.add("open-popup& ...

Unable to alter the pagination's selected page color to grey with material UI pagination components

Currently, I am implementing pagination using material UI. While I have successfully changed the page color to white, I am facing difficulty in changing the selected page color to grey. This issue arises because the background color is dark. import React, ...

Initiate an Ajax call to pre-fetch video content

I've been attempting to download a video from my own source and display a loading message while it's being downloaded. Once the download is complete, I want to hide the loading icon and have the video ready for playback. My issue lies in gettin ...

Executing Javascript prior to Gatsby page load

Currently, I am in the process of converting an HTML template using Bootstrap 5 into a Gatsby template. While the CSS and pages are functioning as expected, I have encountered an issue with the inclusion of a main.js file within the HTML template that need ...

Use JavaScript regex to replace a string only if its length exceeds a certain specified limit

My current approach involves using JavaScript regex to insert an HTML markup for all identified URLs: var exp = /(((|www\.|(http|https|ftp|news|file)+\:\/\/)[&#95;.a-z0-9-]+\.[a-z0-9\/&#95;:@=.+?,##%&~-]*[^.|&bso ...

Configuring webpack for live reloading and Hot Module Replacement on static pages

The title of this post may not be very clear, but I appreciate your patience. I am currently in the process of setting up React for an older Rails application that uses static ERBs. Due to the size of the project, I am gradually transitioning towards a Si ...

Struggling to adjust the timeout to exceed 60 seconds

I have been attempting to set a timeout for 120 seconds or more, but no matter what I try, the requests are timing out after only 60 seconds. Things I have tried include: $.ajax({ url: URL, timeout: 120000, success: function(html){ co ...

How can I integrate ASP.NET Identity with ServiceStack for authorization?

In my search for a solution regarding mutual authentication between ASP.NET MVC and Servicestack, I came across one example which involved utilizing Servicestack's built-in authentication and setting the cookie for old MVC Forms authentication. I am ...

Guide on installing React packages during runtime

My React project has a number of packages that need to be installed, but they take up a lot of disk space. I would like to install them only when necessary, after the user interacts with a specific component that requires these packages. Is there a way t ...

Guide on transforming Json information into the preferred layout and iterating through the loop

Currently, I am diving deep into the world of JSON and feeling a bit puzzled by data formats, arrays, objects, and strings. First things first, I'm in need of data structured like this (on a jQuery page). Would this be considered an object or an arra ...

Can I find a better approach to optimize this code?

How can I refactor this code to move the entire DB query logic into a separate file and only call the function in this current file? passport.use( new GoogleStrategy({ clientID: googleId, clientSecret: clientSecret, callbackURL: ...

Enhancing Material UI v4 Themes using TypeScript

I am attempting to implement my own custom palette option in the theme section, but I am struggling with how to do the augmentation part using TypeScript. So far, I have created a file named "material-ui.d.ts" and inside it, I only have: import { PaletteO ...

Is it possible to conceal the source code within the dist js file using Vue JS?

I am looking to create a detailed logging page that showcases the logs without revealing the specific type of logging. I want to prevent users from accessing the minified vue JS script and easily reading the logged information. Is there a way to implemen ...

I am experiencing issues with launching chromium while running Puppeteer on Windows 11 using node js v19.4

Upon following the installation instructions in the documentation to install puppeteer with npm install puppeteer, I attempted to run the example for downloading a webpage as a PDF. However, every time I try to execute the code, Node.js returns the followi ...