Data from modal form does not get passed to MVC controller

jwebster77
jwebster77 used Ask the Experts™
on
Hi,

I have a button on a tab that when clicked opens a modal form but when I enter data in the textboxes it does not get saved to the database.  The javascript object(taskObj) from the code below gets filled with the data entered but when it reaches the controller and I hover over "ItTask" it does not contain any data.    Consequently, when I let the code run I get an error when it tries to run the stored procedure. What am I doing wrong?  Extra info:  the view was added from "ItTask" actionresult.  Please help.  Thank you.

CONTROLLER:

public ActionResult ItTask()
        {
            return View();
        }

        //Add IT Task
        //public JsonResult AddTask(ITTasksModel ItTask)
        public ActionResult AddTask(ITTasksModel ItTask)
        {
            HelpDeskDBHandle hdDB = new HelpDeskDBHandle();
            hdDB.AddTaskIT(ItTask);
            //return Json(hdDB.AddTaskIT(ItTask), JsonRequestBehavior.AllowGet);
            return View();
        }

        //List IT Tasks
        public JsonResult ListITTasks()
        {
            HelpDeskDBHandle hdDB = new HelpDeskDBHandle();
            return Json(hdDB.GetITTasksList(), JsonRequestBehavior.AllowGet);
        }

Open in new window



VIEW:

@model HelpDeskSupport.Models.ITTasksModel

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>It Tasks</title>

    <script src="~/Scripts/ITTasksJS.js"></script>
</head>
<body>
    <div>
    </div>
</body>
</html>


<div class="container">
    <h2>IT Tasks</h2>
    <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#myModal" onclick="clearTextBox();">Add New Task</button><br /><br />
    <table class="table table-bordered table-hover">
        <thead>
            <tr>
                <th>
                    Number
                </th>
                <th>
                    Description
                </th>
                <th>
                    Enter Date
                </th>
                <th>
                    Assigned To
                </th>
                <th>
                    Estimated Completion
                </th>
                <th>
                    Priority
                </th>
                <th>
                    From
                </th>
                <th>
                    Status
                </th>
            </tr>
        </thead>
        <tbody class="tbody"></tbody>
    </table>
</div>
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal">×</button>
                <h4 class="modal-title" id="myModalLabel">Add IT Task</h4>
            </div>
            <div class="modal-body">
                <form>
                    @*<div class="form-group">
                            <label for="ITNumber">Number</label>
                            <input type="text" class="form-control" id="ITNum" placeholder="Number" disabled="disabled" />
                        </div>*@
                    <div class="form-group">
                        <label for="ITDescription">Description</label>
                        <input type="text" class="form-control" id="ITDescription" placeholder="Description" />
                    </div>
                    <div class="form-group">
                        <label for="ITEnterDate">Enter Date</label>
                        <input type="text" class="form-control" id="ITEnterDate" placeholder="Enter Date" />
                    </div>
                    <div class="form-group">
                        <label for="ITAssignedTo">Assigned To</label>
                        <input type="text" class="form-control" id="ITAssignedTo" placeholder="Assigned To" />
                    </div>
                    <div class="form-group">
                        <label for="ITEstimatedCompletion">Estimated Completion</label>
                        <input type="text" class="form-control" id="ITEstimatedCompletion" placeholder="Estimated Completion" />
                    </div>
                    <div class="form-group">
                        <label for="ITPriority">Priority</label>
                        <input type="text" class="form-control" id="ITPriority" placeholder="Priority" />
                    </div>
                    <div class="form-group">
                        <label for="ITFrom">From</label>
                        <input type="text" class="form-control" id="ITFrom" placeholder="From" />
                    </div>
                    <div class="form-group">
                        <label for="ITStat">Status</label>
                        <input type="text" class="form-control" id="ITStatus" placeholder="Status" />
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="submit" class="btn btn-primary" id="btnAddItTask" onclick="return AddItTask();">Add</button>
                <button type="button" class="btn btn-primary" id="btnUpdate" style="display:none;" onclick="Update();">Update</button>
                <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
            </div>
        </div>
    </div>
</div>

Open in new window



MODEL:

namespace HelpDeskSupport.Models
{
    public class ITTasksModel
    {
        [Key]
        public int ITNumber { get; set; }
        public string ITDescription { get; set; }
        public DateTime ITEnterDate { get; set; }
        public string ITAssignedTo { get; set; }
        public DateTime ITEstimatedCompletion { get; set; }
        public string ITPriority { get; set; }
        public string ITFrom { get; set; }
        public string ITStatus { get; set; }
    }
}

Open in new window



JAVASCRIPT FILE:

//Load Data in Table when documents is ready
//$(document).ready(function () {
//    loadData();
//});

//Load Data function
function loadData() {
    $.ajax({
        url: "/Home/ListITTasks",
        type: "GET",
        contentType: "application/json;charset=utf-8",
        dataType: "json",
        success: function (result) {
            var html = '';
            $.each(result, function (key, item) {
                html += '<tr>';
                html += '<td>' + item.ITDescription + '</td>';
                html += '<td>' + item.ITEnterDate + '</td>';
                html += '<td>' + item.ITAssignedTo + '</td>';
                html += '<td>' + item.ITEstimatedCompletion + '</td>';
                html += '<td>' + item.ITPrioririty + '</td>';
                html += '<td>' + item.ITFrom + '</td>';
                html += '<td>' + item.ITStatus + '</td>';
                //html += '<td><a href="#" onclick="return getbyID(' + item.EmployeeID + ')">Edit</a> | <a href="#" onclick="Delele(' + item.EmployeeID + ')">Delete</a></td>';
                html += '</tr>';
            });
            $('.tbody').html(html);
        },
        error: function (errormessage) {
            alert(errormessage.responseText);
        }
    });
}

//Add IT Task
function AddItTask() {
    var res = validate();
    if (res == false) {
        return false;
    }
    alert("Successful AddITTask1");
    var taskObj = {
        //Number: $('#ITNum').val(),
        Description: $('#ITDescription').val(),
        EnterDate: $('#ITEnterDate').val(),
        AssignedTo: $('#ITAssignedTo').val(),
        EstimatedCompletion: $('#ITEstimatedCompletion').val(),
        Priority: $('#ITPriority').val(),
        From: $('#ITFrom').val(),
        Status: $('#ITStatus').val()
    };
    alert("Successful AddITTask2");
    $.ajax({
        type: "POST",
        data: taskObj, 
        url: "/Tickets/AddTask",
        //data: JSON.stringify(taskObj),     
        //contentType: "application/json;charset=utf-8",
        //dataType: "json",
        success: function (result) {
            //loadData();
            $('#myModal').modal('hide');
        },
        error: function (errormessage) {
            alert(errormessage.responseText);
        }
    });
    alert("Successful AddITTask3");
}

//Function for clearing the textboxes of the add task modal form
function clearTextBox() {
    //$('#ITNum').val("");
    $('#ITDescription').val("");
    $('#ITEnterDate').val("");
    $('#ITAssignedTo').val("");
    $('#ITEstimatedCompletion').val("");
    $('#ITPriority').val("");
    $('#ITFrom').val("");
    $('#ITStatus').val("");
    //$('#btnUpdate').hide();
    //$('#btnAdd').show();
    $('#ITDescription').css('border-color', 'lightgrey');
    $('#ITEnterDate').css('border-color', 'lightgrey');
    $('#ITAssignedTo').css('border-color', 'lightgrey');
    $('#ITEstimatedCompletion').css('border-color', 'lightgrey');
    $('#ITPriority').css('border-color', 'lightgrey');
    $('#ITFrom').css('border-color', 'lightgrey');
    $('#ITStatus').css('border-color', 'lightgrey');
}

//Validation of task modal form using jquery
function validate() {
    var isValid = true;
    if ($('#ITDescription').val().trim() == "") {
        $('#ITDescription').css('border-color', 'Red');
        isValid = false;
    }
    else {
        $('#ITDescription').css('border-color', 'lightgrey');
    }
    if ($('#ITEnterDate').val().trim() == "") {
        $('#ITEnterDate').css('border-color', 'Red');
        isValid = false;
    }
    else {
        $('#ITEnterDate').css('border-color', 'lightgrey');
    }
    if ($('#ITAssignedTo').val().trim() == "") {
        $('#ITAssignedTo').css('border-color', 'Red');
        isValid = false;
    }
    else {
        $('#ITAssignedTo').css('border-color', 'lightgrey');
    }
    if ($('#ITEstimatedCompletion').val().trim() == "") {
        $('#ITEstimatedCompletion').css('border-color', 'Red');
        isValid = false;
    }
    else {
        $('#ITEstimatedCompletion').css('border-color', 'lightgrey');
    }
    if ($('#ITPriority').val().trim() == "") {
        $('#ITPriority').css('border-color', 'Red');
        isValid = false;
    }
    else {
        $('#ITPriority').css('border-color', 'lightgrey');
    }
    if ($('#ITFrom').val().trim() == "") {
        $('#ITFrom').css('border-color', 'Red');
        isValid = false;
    }
    else {
        $('#ITFrom').css('border-color', 'lightgrey');
    }
    if ($('#ITStatus').val().trim() == "") {
        $('#ITStatus').css('border-color', 'Red');
        isValid = false;
    }
    else {
        $('#ITStatus').css('border-color', 'lightgrey');
    }
    return isValid;
}

Open in new window

Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Miguel OzSenior Software Engineer
Top Expert 2009

Commented:
I think you are missing the form that defines how to call the controller/method and post your textbox data as parameter.

See the examples below:
https://weblogs.asp.net/scottgu/asp-net-mvc-preview-5-and-form-posting-scenarios
https://www.c-sharpcorner.com/article/various-ways-of-form-submit-in-asp-net-mvc-part-one/
There are a couple of different ways to go about this, but ultimately it’s not working because you’re not being explicit enough for the MVC pipeline and ModelBinder to figure out what you’re trying to do.

1. Either use the ASPNET MVC naming convention for your controller method (rename it to PostAddTask) or decorate it with the [HttpPost] annotation.

2. The names of your model properties need to be in sync with the names you are posting. Your C# model prefixes everything with IT; your posted object does not.

3. Instead of sending a naked JavaScript object, use the JavaScript FormData object to contain the data you’re trying to send.
//Add IT Task
function AddItTask() {
    var res = validate();
    if (res == false) {
        return false;
    }
    alert("Successful AddITTask1");
    var taskObj = new FormData();
	taskObj.append('ITDescription', $('#ITDescription').val());
	taskObj.append('ITEnterDate', $('#ITEnterDate').val());
	taskObj.append('ITAssignedTo', $('#ITAssignedTo').val());
	taskObj.append('ITEstimatedCompletion', $('#ITEstimatedCompletion').val());
	taskObj.append('ITPriority', $('#ITPriority').val());
	taskObj.append('ITFrom', $('#ITFrom').val());
	taskObj.append('ITStatus', $('#ITStatus').val());

    alert("Successful AddITTask2");
    $.ajax({
        type: "POST",
        data: taskObj, 
        url: "/Tickets/AddTask",
        success: function (result) {
            //loadData();
            $('#myModal').modal('hide');
            alert("Successful AddITTask3");
        },
        error: function (errormessage) {
            alert(errormessage.responseText);
        }
    });
}

Open in new window

(Note: I did this from my phone so some of the code might have gotten a bit mangled.)

That’s all I can think of of the top of my head. Give that a shot and see how it goes.

Author

Commented:
Very helpful!  Your answer and some code skewing made the trick.  Thank you very much!

THis is the code that worked:
CONTROLLER
[HttpPost]
        public ActionResult AddTask(ITTasksModel ItTask)
        {
            HelpDeskDBHandle hdDB = new HelpDeskDBHandle();          
            return Json(hdDB.AddTaskIT(ItTask), JsonRequestBehavior.AllowGet);
        }

JAVASCRIPT:
function AddItTask() {
    var res = validate();
    if (res == false) {
        return false;
    }
    alert("Successful AddITTask1");
    var taskObj = {
        //Number: $('#ITNum').val(),
        ITDescription: $('#ITDescription').val(),
        ITEnterDate: $('#ITEnterDate').val(),
        ITAssignedTo: $('#ITAssignedTo').val(),
        ITEstimatedCompletion: $('#ITEstimatedCompletion').val(),
        ITPriority: $('#ITPriority').val(),
        ITFrom: $('#ITFrom').val(),
        ITStatus: $('#ITStatus').val()
    };
    alert("Successful AddITTask2");
    $.ajax({
        type: "POST",
        url: "/Tickets/AddTask",
        data: JSON.stringify(taskObj),
        //data: taskObj,
        contentType: "application/json;charset=utf-8",
        dataType: "json",
        success: function (result) {
            //loadData();
            $('#myModal').modal('hide');
            alert("Successful ModalHide");
        },
        error: function (errormessage) {
            alert(errormessage.responseText);
        }
    });
    alert("Successful AddITTask3");
}

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial