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 :
public ActionResult InsertData_5()
{
return View();
}
[HttpPost]
public ActionResult InsertData_5(Personal objdata)
{
try
{
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 :
USE [ContosoUniversity1]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
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 :
@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.
@{ 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.