problem storing a modal message in the database

My current project involves displaying data from a database with accept and reject buttons next to each row. When the user clicks on one of these buttons, the value is passed to the controller and saved in the database. Everything was working fine until I tried to implement a popup modal that would only appear when the reject button is clicked and allow the user to add a note. However, I encountered an issue where the modal was passing double the number of data rows instead of just the specific row I was on. I am struggling to figure out how to pass the row ID, the rejected button value, and the message to the controller correctly. Additionally, I attempted to pass the modal within the reject button method in the controller, but it ended up being null. Can anyone provide guidance on what I may be doing wrong here? Is my script portion properly organized and accurate after adding AJAX functionality? Any help or advice would be greatly appreciated. Here is a snippet of my view:

@model AllmyTries.Models.fulfillmentVM


<!-- page content -->


                                    @using (Html.BeginForm("Add_Fulfillment_Reject", "Feedback", FormMethod.Post))
                                    {
                                        @Html.AntiForgeryToken()
                                        <td>
                                            <button id="btnReject" class="btn btn-lg btn-danger" name="button" data-toggle="modal" data-target="#exampleModal" type="submit" onclick="reject(0)" value="0">Reject</button>
                                            @Html.Hidden("Request_ID", Model._Requests[i].Request_ID)
                                            @Html.Hidden("Status", Model._Requests[i].Status, new { id = "myEdit", value = "" })
                                        </td>

                                        <div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
                                            <div class="modal-dialog" role="document">
                                                <div class="modal-content">
                                                    <div class="modal-header">
                                                        <h5 class="modal-title" id="exampleModalLabel">New message</h5>
                                                        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                                                            <span aria-hidden="true">&times;</span>
                                                        </button>
                                                    </div>
                                                    <div class="modal-body">
                                                        <form id="myform">

                                                            <div class="form-group">
                                                                <textarea class="form-control" id="message-text"></textarea>
                                                            </div>
                                                        </form>
                                                    </div>
                                                    <div class="modal-footer">
                                                        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                                                        <input type="reset" value="submit" class="btn btn-success" id="finalSave" />

                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    }


<!-- /page content -->


@section Scripts {
    <script>

        $('[name = "button"]').click(function () {
            $('[name = "Status"]').val($('[name = "button"]').val());

        })

        $(document).ready(function () {
            $('#finalSave').click(function () {
                var dataform = $('#myform').serialize();
                $.ajax({
                    type: 'POST',
                    url: '/Feedback/Add_Fulfillment_Reject',
                    data: dataform,
                    success: function () {
                        $('#exampleModal').modal('hide');
                    }

                })

            })
        })

    </script>
}

This is an excerpt from the controller:


        #region fulfillment
        [HttpPost]
        public ActionResult Add_Fulfillment_Accept(int Request_ID, int? Status)
        {
            var user = db.TBL_Request.Find(Request_ID);

            user.Inserted_by = Status ?? 0;

            db.SaveChanges();
            return RedirectToAction("Index");
        }
//this is the one with the issue 
        [HttpPost]
        public ActionResult Add_Fulfillment_Reject(fulfillmentVM vM)
        {
            //save the status
            //save the note


            db.SaveChanges();
            return RedirectToAction("Index");
        }
        #endregion


    }

Answer №1

To ensure proper functionality, update your Javascript code to submit only the textarea within the <form id="myForm"> to the controller action that expects a fulfillmentVM object. Modify your Html.Hidden fields to use Html.HiddenFor, which will bind the values on submission.

In order to enable model binding, utilize TextAreaFor instead of a simple textarea and confirm that your viewmodel includes a corresponding property for it.

@Html.HiddenFor(m => m._Requests[i].Request_ID)
@Html.HiddenFor(m => m._Requests[i].Status, new { id = "myEdit", value = "" })
@Html.TextAreaFor(m => m.RejectMessage, htmlAttributes: new { @class = "form-control" })

It is unnecessary to include the <form id="myForm"> tags in your code.

Ensure that the button remains as a submit button so that it posts to the Add_Fulfillment_Reject controller while passing all bound values for your fulfillmentVM.

Placement of the form

Personally, I recommend placing the form just before the text box, along with moving the hidden fields there as well. End the form right after the submit button.

@using (Html.BeginForm("Add_Fulfillment_Reject", "Feedback", FormMethod.Post))
{
    @Html.HiddenFor(m => m._Requests[i].Request_ID)
    @Html.HiddenFor(m => m._Requests[i].Status, new { id = "myEdit", value = "" })
    @Html.TextAreaFor(m => m.RejectMessage, htmlAttributes: new { @class = "form-control" })
    // rest of modal code
    <input type="submit" class="btn btn-success" id="finalSave" />
} // end form

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

Display different website content in a div when the page loads

My current project involves creating a team website hosted on a LAMP server. This website includes various "team pages" dedicated to different age groups. I am facing the challenge of integrating "external" content (from another page within my domain) into ...

Problematic Mouse Position Detection in FireFox

I'm encountering a problem with fetching mouse positions on the Firefox browser. It seems like there's an issue in my code causing it not to work correctly. Here is what I have done so far. Javascript Code: function GetMousePosition(event){ ...

Transitioning from the traditional LeftNav menu style to the more versatile composability feature using Reactjs with Material-ui

Hey there, I'm facing a bit of confusion while trying to create a LeftNav menu using material-ui. I recently joined this project and updated reactjs and material-ui. Unfortunately, many things related to LeftNav in material-ui have been deprecated, ...

Updating CSS in response to a button click using JavaScript: A step-by-step guide

Currently, I am in the process of creating a basic website with bootstrap5 (no JS at the moment). One issue I am facing is when I shrink the screen to the point where the navigation bar transforms into a burger button. Whenever I click on the burger button ...

Creating a custom AngularJS filter to search within an array of objects

I'm currently working with an object in my project: {"A":[],"B":[],"C":[],"D":[],"E":[],"F":[{"name":"Fargo","id":29}],"G":[],"H":[],"I":[],"J":[],"K":[],"L":[],"M":[],"N":[],"O":[],"P":[],"Q":[],"R":[],"S":[{"name":"Sullivan","id":23},{"name":"Sven" ...

How can I retrieve an empty object from the database using Angular 5?

Hey there! I'm facing a little issue that I need help solving. I asked a question before when things weren't clear, but now they are (you can find the previous question here). I'll share my code and explain what I want to achieve shortly. H ...

The error message "Type Error: val.toString is not a function - mysql npm" indicates

I'm encountering an issue with the 'mysql' package in NPM on a nodeJS backend and I'm puzzled by this error message: TypeError: val.toString is not a function at Object.escape (/Applications/MAMP/htdocs/nodeJS_livredor/node_modules/sql ...

What is the best way to align a label, input box, and a small search image on the same line

I'm currently working on developing a mobile page using jQuery Mobile version 1.4.4. I've managed to get the label and input box to display correctly in one line, but I'm encountering an issue with the small search image appearing on the nex ...

How can I create a collection in C# that allows for duplicate values for both characters and integers in pairs?

I am looking to tally the occurrence of each character in a string, maintaining the order in which they appear. For instance, in the string "aabaccbb" there are two 'a's, one 'b', one 'a', two 'c's, and two ...

What is the difference in memory usage for JavaScript objects between Node.js and Chrome?

It's puzzling to me why the size of the heap is twice as large as expected. I meticulously constructed a binary tree with perfection. I suspect v8 recognizes that each node consists of 3 fields. function buildTree(depth) { if (depth === 0) return n ...

Issue with Dijit form fields failing to render correctly following dojo.destroy and dojo.place operations

Within my form, there is a table labeled as table0 which contains various dijit form controls. Additionally, there are buttons for adding and removing tables where each new table is assigned an ID incremented by 1. For instance, the first click on the add ...

Items added to a form using jQuery will not be submitted when the form is posted

Issues with posting data from dynamically appended options in a form select using jQuery have been noticed. When an appended option is selected and the form is submitted, the value does not get posted (in this case, in an email template). Adding another no ...

Using jQuery to swap out sections of a HTML tag

Similar Question: Use of jQuery for Modifying an HTML Tag? After extensive research, I have not come across a solution that fits my specific requirements. My objective is to replace a part of an HTML tag without completely replacing the entire tag. To ...

Is it possible to utilize the addition assignment operator (`+=`) to modify the `transform:rotate('x'deg);` CSS property using

This is the code I have been working on: #move{ height:70px; width:70px; border:2px solid black; border-radius:15px; } <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <input type="button" val ...

What is the best way to delete a subdocument from a main document when either condition x is true or condition y is true?

A subdocument referred to as Bets is embedded into an array of a property on another model called Users. When a user removes a friend, all associated bets with that specific user should also be deleted from the User document (the user who was friends with ...

Real-time functionality in React component and Apollo Client is not functioning as expected

I am struggling to develop a user system as it is not working in real-time, causing confusion for me. To illustrate my problem and code, I have set up a sample Sandbox. Please note that this example does not include any validation features and is solely f ...

Is the functionality compatible with all browsers even though <div /> is not recognized as a proper HTML element?

Can the code $("<div />").appendTo($mySelector) be relied upon for safety and cross-browser compatibility, considering that <div /> is not a valid HTML element? I pose this question because it seems much simpler to use than $("<div><d ...

Struggling with transferring a value between two input fields using jQuery

I'm currently working on a project to create a simple "to-do list" and I've encountered an issue that seems pretty basic. I am trying to pass the main input from #myInput at the top, down to the next line below, but I'm facing some challenge ...

Encountering NPM Abortion Issue in Node.js

I am a beginner in node.js and have successfully installed it. However, when I try to initialize npm, I encounter an error that causes it to abort. My system has high memory capacity with 32GB RAM and 1TB HD. Although the 'npm -v' command works ...

Why doesn't express.js throw an error when the variable 'app' is used within its own definition?

When working with express.js, I find it puzzling that createApplication() does not throw an error. This is because it uses app.handle(...) within an anonymous function that defines the same variable 'app'. I attempted to replicate this in jsFidd ...