2

I have used Master Entry Details in ASP.NET to enter project components and its component activities into table component and component_activity, but while saving the data the db.SaveChanges return me an error which i could not understand how to solve it. please help me. thanks

my Controller:

[HttpPost]
    public JsonResult SaveComponent(PcomponentsVM pc)
    {
        try
        {
            bool status = false;
            if (ModelState.IsValid)
            {
                using (Entities db = new Entities())
                {

                    Pcomponent comp = new Pcomponent { title = pc.title, description = pc.description };
                    foreach (var i in pc.ComponentActivities)
                    {
                        comp.ComponentActivities.Add(i);
                    }

                    db.Pcomponents.Add(comp);
                    db.SaveChanges();
                    status = true;
                }
            }
            else
            {
                status = false;
            }
            return new JsonResult { Data = new { status = status } };
        }

        catch (Exception ex)
        {
            return null;
        }
    }

my Component Model View

public partial class Pcomponent
{
    public Pcomponent()
    {
        this.ComponentActivities = new HashSet<ComponentActivity>();
    }
    [Key]
    public int id { get; set; }
    public int project_id { get; set; }
    public string title { get; set; }
    public string description { get; set; }

    public virtual ICollection<ComponentActivity> ComponentActivities { get; set; }
}

My Component Acivitiy Model

 public partial class ComponentActivity
{
    [Key]
    public int id { get; set; }
    public int component_id { get; set; }
    public int activity_id { get; set; }
    public int contracted_unit { get; set; }
    public int unit { get; set; }
    public decimal unit_cost { get; set; }
    public virtual Pcomponent Pcomponent { get; set; }
}

My Virtual View Model

 public  class PcomponentsVM
{
    public int id { set; get; }
    public string title { set; get; }
    public int project_id { set; get; }
    public string description { set; get; }
    public List<ComponentActivity> ComponentActivities { get; set; }

}

My Script

<script>
       $(document).ready(function () {
        var orderItems = [];
        //Add button click function
        $('#add').click(function () {
            //Check validation of order item
            var isValidItem = true;
            if ($('#activityName').val().trim() == '') {
                isValidItem = false;
                $('#activityName').siblings('span.error').css('visibility', 'visible');
            }
            else {
                $('#activityName').siblings('span.error').css('visibility', 'hidden');
            }

            if (!($('#cunit').val().trim() != '' && !isNaN($('#cunit').val().trim()))) {
                isValidItem = false;
                $('#cunit').siblings('span.error').css('visibility', 'visible');
            }
            else {
                $('#cunit').siblings('span.error').css('visibility', 'hidden');
            }

            if (!($('#unit').val().trim() != '' && !isNaN($('#unit').val().trim()))) {
                isValidItem = false;
                $('#unit').siblings('span.error').css('visibility', 'visible');
            }
            else {
                $('#rate').siblings('span.error').css('visibility', 'hidden');
            }

            //Add item to list if valid
            if (isValidItem) {
                orderItems.push({
                    activity_id: parseInt($('#activityName').val().trim()),
                    contracted_unit: parseInt($('#cunit').val().trim()),
                    unit: parseInt($('#unit').val().trim()),
                    unit_cost: parseInt($('#cunit').val().trim()) * parseInt($('#unit').val().trim())
                });

                //Clear fields
                $('#activityName').val('').focus();
                $('#cunit,#unit').val('');

            }
            //populate order items
            GeneratedItemsTable();

        });
        //Save button click function
        $('#submit').click(function () {
            //validation of order
            var isAllValid = true;
            if (orderItems.length == 0) {
                $('#orderItems').html('<span style="color:red;">Please add order items</span>');
                isAllValid = false;
            }

            if ($('#title').val().trim() == '') {
                $('#title').siblings('span.error').css('visibility', 'visible');
                isAllValid = false;
            }
            else {
                $('#title').siblings('span.error').css('visibility', 'hidden');
            }

           /* if ($('#orderDate').val().trim() == '') {
                $('#orderDate').siblings('span.error').css('visibility', 'visible');
                isAllValid = false;
            }
            else {
                $('#orderDate').siblings('span.error').css('visibility', 'hidden');
            }*/

            //Save if valid
            if (isAllValid) {
                var data = {
                    title: $('#title').val().trim(),
                   // OrderDate: $('#orderDate').val().trim(),
                    //Sorry forgot to add Description Field
                    description: $('#description').val().trim(),
                    ComponentActivities: orderItems
                }

                $(this).val('Please wait...');

                $.ajax({
                    url: '/Pcomponents/SaveComponent',
                    type: "POST",
                    data: JSON.stringify(data),
                    dataType: "JSON",
                    contentType: "application/json",
                    success: function (d) {
                        //check is successfully save to database 
                        if (d.status == true) {
                            //will send status from server side
                            alert('Successfully done.');
                            //clear form
                            orderItems = [];
                            $('#title').val('');
                            //$('#orderDate').val('');
                            $('#orderItems').empty();
                        }
                        else {
                            alert('Failed');
                        }
                        $('#submit').val('Save');
                    },
                    error: function () {
                        alert('Error. Please try again.');
                        $('#submit').val('Save');
                    }
                });
            }

        });
        //function for show added items in table
        function GeneratedItemsTable() {
            if (orderItems.length > 0)
            {
                var $table = $('<table/>');
                $table.append('<thead><tr><th>Activity Name</th><th>Contracted Unit</th><th>Unit</th><th>Total</th><th></th></tr></thead>');
                var $tbody = $('<tbody/>');
                $.each(orderItems, function (i, val) {
                    var $row = $('<tr/>');
                    $row.append($('<td/>').html(val.activity_id));
                    $row.append($('<td/>').html(val.contracted_unit));
                    $row.append($('<td/>').html(val.unit));
                    $row.append($('<td/>').html(val.unit_cost));
                    var $remove = $('<a href="#">Remove</a>');
                    $remove.click(function (e) {
                        e.preventDefault();
                        orderItems.splice(i, 1);
                        GeneratedItemsTable();
                    });
                    $row.append($('<td/>').html($remove));
                    $tbody.append($row);
                });
                console.log("current", orderItems);
                $table.append($tbody);
                $('#orderItems').html($table);
            }
            else {
                $('#orderItems').html('');
            }
        }
    });

</script>

Error

Error After Click on Button Save

View Screen Short

enter image description here

ZKF3340320
  • 171
  • 2
  • 9
  • Is `url: '/Pcomponents/SaveComponent'` on JS script worked fine? I suspected `return new JsonResult { Data = new { status = status } };` returning new instance of JsonResult which triggering new exception, since `db.SaveChanges()` totally unrelated with "action method not found" here. – Tetsuya Yamamoto Sep 21 '16 at 07:50
  • What happens when you type `/Pcomponents/SaveComponent` in the address bar? –  Sep 21 '16 at 08:15
  • while i type it in URl i got the error The resource cannot be found. – ZKF3340320 Sep 21 '16 at 08:20
  • Is your controller marked public? –  Sep 21 '16 at 08:21
  • Yes it is " public class PComponentsController : Controller" – ZKF3340320 Sep 21 '16 at 08:28
  • after submitting Save button the error for db.SaveChanges() is " An exception of type 'System.Data.Entity.Infrastructure.DbUpdateException' occurred in EntityFramework.dll but was not handled in user code " – ZKF3340320 Sep 21 '16 at 08:33
  • please help me Stephen Muecke, Tetsuya Yamamato – ZKF3340320 Sep 21 '16 at 09:36
  • @user3340320, The image of the error message states there is no `public` method, yet your claiming there is so its not clear what the issue is (and your have not shown the view). However 95% of this code is unnecessary and indicates you do not understand how MVC works. MVC comes with validation built in so most of the code in `$('#add').click(function () {` not just bad code, its unnecessary. Generating the whole table each time instead of just adding a new row is unnecessary. –  Sep 21 '16 at 10:04
  • Even using ajax in this case is unnecessary as all this can be done far more simply by generating your view correctly in the first place. For some options of what you can do, refer the answers [here](http://stackoverflow.com/questions/29837547/set-class-validation-for-dynamic-textbox-in-a-table/29838689#29838689) and [here](http://stackoverflow.com/questions/29837547/set-class-validation-for-dynamic-textbox-in-a-table/29838689#29838689) –  Sep 21 '16 at 10:06

1 Answers1

0

This works:

DDL:

USE [Breaz]
GO
/****** Object:  Table [dbo].[ComponentActivity]    Script Date: 9/22/2016 4:33:18 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[ComponentActivity](
    [id] [int] IDENTITY(1,1) NOT NULL,
    [component_id] [int] NULL,
    [activity_id] [int] NULL,
    [contracted_unit] [int] NULL,
    [unit] [int] NULL,
    [unit_cost] [money] NULL,
 CONSTRAINT [PK_ComponentActivity] PRIMARY KEY CLUSTERED 
(
    [id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[Pcomponent]    Script Date: 9/22/2016 4:33:18 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[Pcomponent](
    [id] [int] IDENTITY(1,1) NOT NULL,
    [project_id] [int] NULL,
    [title] [varchar](10) NULL,
    [description] [varchar](10) NULL,
 CONSTRAINT [PK_Pcomponent] PRIMARY KEY CLUSTERED 
(
    [id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[PcomponentsVM]    Script Date: 9/22/2016 4:33:18 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[PcomponentsVM](
    [id] [int] IDENTITY(1,1) NOT NULL,
    [title] [varchar](10) NULL,
    [project_id] [int] NULL,
    [description] [varchar](10) NULL,
 CONSTRAINT [PK_PcomponentsVM] PRIMARY KEY CLUSTERED 
(
    [id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO
SET ANSI_PADDING OFF
GO
ALTER TABLE [dbo].[ComponentActivity]  WITH CHECK ADD  CONSTRAINT [FK_ComponentActivity_Pcomponent] FOREIGN KEY([component_id])
REFERENCES [dbo].[Pcomponent] ([id])
GO
ALTER TABLE [dbo].[ComponentActivity] CHECK CONSTRAINT [FK_ComponentActivity_Pcomponent]
GO
ALTER TABLE [dbo].[ComponentActivity]  WITH CHECK ADD  CONSTRAINT [FK_ComponentActivity_PcomponentsVM] FOREIGN KEY([component_id])
REFERENCES [dbo].[PcomponentsVM] ([id])
GO
ALTER TABLE [dbo].[ComponentActivity] CHECK CONSTRAINT [FK_ComponentActivity_PcomponentsVM]
GO
ALTER TABLE [dbo].[PcomponentsVM]  WITH CHECK ADD  CONSTRAINT [FK_PcomponentsVM_PcomponentsVM] FOREIGN KEY([id])
REFERENCES [dbo].[PcomponentsVM] ([id])
GO
ALTER TABLE [dbo].[PcomponentsVM] CHECK CONSTRAINT [FK_PcomponentsVM_PcomponentsVM]
GO

Models after edmx

public partial class ComponentActivity
{
    public int id { get; set; }
    public Nullable<int> component_id { get; set; }
    public Nullable<int> activity_id { get; set; }
    public Nullable<int> contracted_unit { get; set; }
    public Nullable<int> unit { get; set; }
    public Nullable<decimal> unit_cost { get; set; }

    public virtual Pcomponent Pcomponent { get; set; }
    public virtual PcomponentsVM PcomponentsVM { get; set; }
}

public partial class Pcomponent
{
    public Pcomponent()
    {
        this.ComponentActivities = new HashSet<ComponentActivity>();
    }

    public int id { get; set; }
    public Nullable<int> project_id { get; set; }
    public string title { get; set; }
    public string description { get; set; }

    public virtual ICollection<ComponentActivity> ComponentActivities { get; set; }
}

public partial class PcomponentsVM
{
    public PcomponentsVM()
    {
        this.ComponentActivities = new HashSet<ComponentActivity>();
    }

    public int id { get; set; }
    public string title { get; set; }
    public Nullable<int> project_id { get; set; }
    public string description { get; set; }

    public virtual ICollection<ComponentActivity> ComponentActivities { get; set; }
    public virtual PcomponentsVM PcomponentsVM1 { get; set; }
    public virtual PcomponentsVM PcomponentsVM2 { get; set; }
}

This is the controller:

public class PcomponentsController : Controller
{
    public ActionResult SaveComponent()
    {
        BreazEntities23 e = new BreazEntities23();
        var pcComponentsVM = e.PcomponentsVMs.Find(1);
        return View(pcComponentsVM);
    }

    [HttpPost]
    public JsonResult SaveComponent(PcomponentsVM pc)
    {
        try
        {
            bool status = false;
            if (ModelState.IsValid)
            {
                using (BreazEntities23 db = new BreazEntities23())
                {
                    //Just fix this..
                    //Pcomponent comp = new Pcomponent { title = pc.title, description = pc.description };
                    //foreach (var i in pc.ComponentActivities)
                    //{
                    //    comp.ComponentActivities.Add(i);
                    //}

                    //db.Pcomponents.Add(comp);
                    //db.SaveChanges();
                    status = true;
                    //change this to status = false to see different message
                    //status = false;
                }
            }
            else
            {
                status = false;
            }
            return new JsonResult { Data = new { status = status } };
        }

        catch (Exception ex)
        {
            return null;
        }
    }
}

This is the view:

@model Testy2.PcomponentsVM

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>SaveComponent</title>
    @Scripts.Render("~/bundles/jquery")
    @*@Scripts.Render("~/bundles/jqueryval")*@
    <script>
        $(document).ready(function () {
            var orderItems = [];
            //Add button click function
            $('#add').click(function () {
                //Check validation of order item
                var isValidItem = true;
                //if ($('#activityName').val().trim() == '') {
                //    isValidItem = false;
                //    $('#activityName').siblings('span.error').css('visibility', 'visible');
                //}
                //else {
                //    $('#activityName').siblings('span.error').css('visibility', 'hidden');
                //}

                //if (!($('#cunit').val().trim() != '' && !isNaN($('#cunit').val().trim()))) {
                //    isValidItem = false;
                //    $('#cunit').siblings('span.error').css('visibility', 'visible');
                //}
                //else {
                //    $('#cunit').siblings('span.error').css('visibility', 'hidden');
                //}

                //if (!($('#unit').val().trim() != '' && !isNaN($('#unit').val().trim()))) {
                //    isValidItem = false;
                //    $('#unit').siblings('span.error').css('visibility', 'visible');
                //}
                //else {
                //    $('#rate').siblings('span.error').css('visibility', 'hidden');
                //}

                //Add item to list if valid
                if (isValidItem) {
                    orderItems.push({
                        activity_id: parseInt($('#activityName').val().trim()),
                        contracted_unit: parseInt($('#cunit').val().trim()),
                        unit: parseInt($('#unit').val().trim()),
                        unit_cost: parseInt($('#cunit').val().trim()) * parseInt($('#unit').val().trim())
                    });

                    //Clear fields
                    $('#activityName').val('').focus();
                    $('#cunit,#unit').val('');

                }
                //populate order items
                GeneratedItemsTable();

            });
            //Save button click function
            $('#mit').click(function () {
                //validation of order
                var isAllValid = true;
                //if (orderItems.length == 0) {
                //    $('#orderItems').html('<span style="color:red;">Please add order items</span>');
                //    isAllValid = false;
                //}

                //if ($('#title').val().trim() == '') {
                //    $('#title').siblings('span.error').css('visibility', 'visible');
                //    isAllValid = false;
                //}
                //else {
                //    $('#title').siblings('span.error').css('visibility', 'hidden');
                //}

                //Save if valid
                if (isAllValid) {
                    var data = {
                        title: $('#title').val().trim(),
                        // OrderDate: $('#orderDate').val().trim(),
                        //Sorry forgot to add Description Field
                        description: $('#description').val().trim(),
                        ComponentActivities: orderItems
                    }

                    $(this).val('Please wait...');

                    $.ajax({
                        url: '/Pcomponents/SaveComponent',
                        type: "POST",
                        data: JSON.stringify(data),
                        //dataType: "JSON",
                        contentType: "application/json",
                        success: function (d) {
                            alert("success");
                            //check is successfully save to database
                            if (d.status == true) {
                            //    //will send status from server side
                                alert('Status is true.');
                            //    //clear form
                            //    orderItems = [];
                            //    $('#title').val('');

                            //    $('#orderItems').empty();
                            }
                            else {
                                alert('Status is false.');
                            }
                            //$('#submit').val('Save');
                        },
                        error: function () {
                            alert('Error. Please try again.');
                            $('#submit').val('Save');
                        }
                    });
                }

            });
            //function for show added items in table
            function GeneratedItemsTable() {
                if (orderItems.length > 0) {
                    var $table = $('<table/>');
                    $table.append('<thead><tr><th>Activity Name</th><th>Contracted Unit</th><th>Unit</th><th>Total</th><th></th></tr></thead>');
                    var $tbody = $('<tbody/>');
                    $.each(orderItems, function (i, val) {
                        var $row = $('<tr/>');
                        $row.append($('<td/>').html(val.activity_id));
                        $row.append($('<td/>').html(val.contracted_unit));
                        $row.append($('<td/>').html(val.unit));
                        $row.append($('<td/>').html(val.unit_cost));
                        var $remove = $('<a href="#">Remove</a>');
                        $remove.click(function (e) {
                            e.preventDefault();
                            orderItems.splice(i, 1);
                            GeneratedItemsTable();
                        });
                        $row.append($('<td/>').html($remove));
                        $tbody.append($row);
                    });
                    console.log("current", orderItems);
                    $table.append($tbody);
                    $('#orderItems').html($table);
                }
                else {
                    $('#orderItems').html('');
                }
            }
        });

    </script>
</head>
<body>
    @using (Html.BeginForm()) 
    {
        @Html.AntiForgeryToken()

        <div class="form-horizontal">
            <h4>PcomponentsVM</h4>
            <hr />
            @Html.ValidationSummary(true)

            @*<div class="form-group">
                @Html.LabelFor(model => model.title, new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.EditorFor(model => model.title)
                    @Html.ValidationMessageFor(model => model.title)
                </div>
            </div>

            <div class="form-group">
                @Html.LabelFor(model => model.project_id, new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.EditorFor(model => model.project_id)
                    @Html.ValidationMessageFor(model => model.project_id)
                </div>
            </div>

            <div class="form-group">
                @Html.LabelFor(model => model.description, new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.EditorFor(model => model.description)
                    @Html.ValidationMessageFor(model => model.description)
                </div>
            </div>*@

            <div>
                <div>Activity Name</div>
                <div><input type="text" id="activityName" /></div>
                <div><input type="text" id="cunit" /></div>
                <div><input type="text" id="unit" /></div>
            </div>
            <div id="title"></div>
            <div id="orderItems"></div>
            <div id="description"></div>

            <table/>

            <div class="form-group">
                <div class="col-md-offset-2 col-md-10">
                    <input id="add" type="button" value="Add" class="btn btn-default" />
                    <input id="mit" type="button" value="Submit" class="btn btn-default" />
                </div>
            </div>
        </div>
    }

    <div>
        @Html.ActionLink("Back to List", "Index")
    </div>
</body>
</html>
kblau
  • 2,094
  • 1
  • 8
  • 20