Click here to Skip to main content
15,884,838 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi I wants to save data to db by ajax in ASP.NET MVC. I read very article and write them in my project, but I face to wrong.
I don’t know what it works properly.
For example :

My code in controller :
C#
public ActionResult InsertData_5()
{
    return View();
}

[HttpPost]
public ActionResult InsertData_5(Personal objdata)
{
    try
    {
        //SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings[connectionString].ToString());
        string constr = "Data Source=192.168.100.1;Initial Catalog=ContosoUniversity1;Persist Security Info=True;User ID=sa;Password=Abhar70";
        SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings[constr].ToString());

        con.Open();
        SqlCommand cmd = new SqlCommand("InsertData_SP", con);
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.Parameters.AddWithValue("@FirstName", objdata.FirstName);
        cmd.Parameters.AddWithValue("@LastName", objdata.LastName);
        cmd.Parameters.AddWithValue("@Phone", objdata.Phone);
        cmd.ExecuteNonQuery();
        con.Close();

    }
    catch (Exception)
    {
        throw;
    }
    
    return View("InsertData_5");
}

+++++++++++++++++
Contains of Store Procedure :
SQL
USE [ContosoUniversity1]
GO
/****** Object:  StoredProcedure [dbo].[InsertData_SP]    Script Date: 02/18/2020 15:04:34 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- Batch submitted through debugger: SQLQuery1.sql|0|0|C:\Users\Administrator\AppData\Local\Temp\~vsF4A9.sql
ALTER PROCEDURE [dbo].[InsertData_SP]
(
    @FirstName nvarchar(MAX),
    @LastName nvarchar(MAX),
    @Phone nvarchar(MAX)
)
AS
BEGIN
    INSERT INTO Personal_tbl2
    (
        FirstName
        ,LastName
        ,Phone
    )
    Values
    (
        @FirstName
        ,@LastName
        ,@Phone
    )
END

+++++++++++++++++
Contains of view . file : InsertData_5.cshtml :
Razor
@model ContosoUniversity.Models.Personal

@using System.Web.Optimization;

@{
    ViewBag.Title = "InsertData_5";
}

<h2>Index</h2>

<div id="divEmp">

    @using (Ajax.BeginForm("InsertData_5", "Post", new AjaxOptions { HttpMethod = "POST", UpdateTargetId = "divEmp" }))
    {
        <table>
        <tbody>
            <tr>
                <td>FirstName</td>
                <td>                    
                </td>
            </tr>
            <tr>
                <td>LastName</td>
                <td>                    
                </td>
            </tr>
            <tr>
                <td>Phone</td>
                <td>                    
                </td>
            </tr>
            <tr>
                <td>                    
                </td>
            </tr>
        </tbody>
        </table>
        
        <script>
            $(document).ready(function () {
                $("#btnsubmit").click(function () {
                    $.ajax(
                    {
                        type: "POST",
                        url: "Home/InsertData_5",
                        data: {
                            FirstName: $("#txtFirstName").val(),
                            LastName: $("#txtLastName").val(),
                            Phone: $("#txtPhone").val()
                        }

                    });

                });
            });
        </script>
    }
</div>

++++++++++++++++
Contains of file : Index.cshtml :
I have a button in this file. When program run, I click button. It receive data. But don’t store in db.
Razor
@{ ViewBag.Title = "first page";  }
<div class="jumbotron">
    <h1>aa</h1>
</div>

<div class="row">
    <div class="col-md-4">
        <div class="navbar-collapse collapse">
            <ul class="btn btn-default">
                <li>@Html.ActionLink("save by Ajax", "InsertData_5", "Home")</li>            
            </ul>   
        </div>
    </div>
</div>

What should I do?
thanks

What I have tried:

I read very article and write them in my project, but I face to wrong.
I don’t know what it works properly.
Posted
Updated 8-Jun-21 23:31pm
v2
Comments
Richard Deeming 18-Feb-20 8:01am    
I've tried to fix your code formatting, but some of your code seems to have disappeared. There are no <input> tags, @Html.TextBoxFor or @Html.EditorFor calls anywhere in your InsertData_5.cshtml view, so there won't be any data to submit.

You also haven't described what the problem is. You need to use your browser's developer tools to examine the AJAX request to see what error you're getting in the response.

Also, a web application should NEVER use sa to connect to SQL Server. That's an unlimited user which could be used to destroy your database, your server, or possibly even your entire network. Use a specific account for your application which has only the permissions required by your application.

And I hope that's not your real sa password that you've just posted to a public forum!
phil.o 18-Feb-20 8:02am    
catch (Exception){    throw;}
is counter-productive since you catch the exception and immediately throw an new empty one without any context it without using its informations. The prior context of initial exception is lost. Try to do something useful in your catch block: log the exception somewhere with its details (message, stack trace) to have a better insight about what is happening.
Richard Deeming 18-Feb-20 8:30am    
Not quite. throw; on its own re-throws the original exception, preserving the stack trace.

There's still no point in catching an exception if you're just going to re-throw it. But it's not quite as bad as you suggest. :)
phil.o 18-Feb-20 8:47am    
Thanks for the update Richard. I thought remembering an old article dealing with that; my memory must begin to decline.
ZurdoDev 18-Feb-20 16:03pm    
We don't know what's wrong either because you didn't tell us what the error is and I'm terrible at guessing errors.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900