簡體   English   中英

使用 jquery 將數據傳遞給 MVC 中的存儲過程

[英]Passing data to stored procedure in MVC using jquery

我是 Jquery 的新手。我想通過 Ajax 將數據傳遞到我的 SQL 數據庫。

Controller 內部:GetCountry 方法從數據庫 proc 中獲取國家列表

public JsonResult GetCountries()
        {
            using(var db = GetContxt())
            {
                var eventCountries = db.Database.SqlQuery<LocationModel>(String.Format("Location.spGetCountries")).ToList();
                return new JsonResult { Data = eventCountries, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
            }
        }

以及將數據發送到數據庫的方法:

[HttpPost]
        public JsonResult SavePatient(LocationModel locationModel)
        {
            string connection = ConfigurationManager.ConnectionStrings["EnrollmentEntity"].ConnectionString;

            using (SqlConnection conn = new SqlConnection(connection))
            {
                SqlCommand cmd = new SqlCommand("Profile.spAddPatientProfile", conn);
                cmd.CommandType = CommandType.StoredProcedure;

                cmd.Parameters.Add(new SqlParameter("@FirstName", locationModel.FirstName));
                cmd.Parameters.Add(new SqlParameter("@LastName", locationModel.LastName));
                cmd.Parameters.Add(new SqlParameter("@IDNumber", locationModel.ID_Number));
               
                cmd.Parameters.Add(new SqlParameter("@Line1", locationModel.Line1));
                cmd.Parameters.Add(new SqlParameter("@Line2", locationModel.Line2));
                cmd.Parameters.Add(new SqlParameter("@CountryIDFK", Int32.Parse(locationModel.CountryIDFK)));
       

                cmd.Parameters.Add(new SqlParameter("@Message", SqlDbType.VarChar, 250)).Direction = ParameterDirection.Output;

                try
                {
                    conn.Open();
                    cmd.ExecuteNonQuery();
                    locationModel.Message = Convert.ToString(cmd.Parameters["@Message"].Value);

                    conn.Close();
                }
                catch (Exception e)
                {

                    Console.WriteLine(e.Message);
                }
               
            }
            return new JsonResult { Data = locationModel, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
            
        }

現在這是我的 Ajax 方法,我想將數據發送到我的 controller 方法

function SaveButton()
    {

        $.ajax({
            url: "/Home/SavePatient",
            type: "POST",
            data: $("#frmHome").serialize(),
            async: false,
            error: function (xhr, status, error)
            {
                alert("was not successful xhr: " + xhr.value + " status: " + status.value + " error: " + error.value);
            },
            success: function (Record)
            {
                alert("was successful");
            }
        })

    }

這些是我的 HTML 元素 textboxfor 和 dropdownListfor

    @{
        ViewBag.Title = "Home Page";
    }
    
    @using PatientEnrollmentVS.Models;
    @model LocationModel
    
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    
    @using (Html.BeginForm("SavePatient", "Home", FormMethod.Post, new { @id = "frmHome" }))
    {
        <div class="row">
            <label>First Name</label>
            @Html.TextBoxFor(x => x.FirstName, new { @class = "select-block" })

            <label>Last Name</label>
            @Html.TextBoxFor(x => x.LastName, new { @class = "select-block" })
        </div>
    
        <div class="row">
            <label>ID Number</label>
            @Html.TextBoxFor(x => x.ID_Number, new {@class = "select-block"})
        </div>
        
        <div class="row">
            <label>DateOfBirth</label>
            @Html.TextBoxFor(x => x.DateOfBirth, new { @class = "select-block" })
        </div>

<div class="row">
        <label>Countries</label>
        @Html.DropDownListFor(x => x.CountryId, new List<SelectListItem>()
            { new SelectListItem()
                {
                    Value = Model.CountryId,
                    Text = Model.CountryName,
                    Selected = true
                }
            }, "0", new { id = "dllGetCountries", @class = "select-block", name = "Countries" })

        </div>
        <div class="row">
            <input type="button" value="Save Event" class="btn btn-primary" onclick="SaveButton()" />
        </div>
var valdata = $("#frmHome").serialize();    
            $.ajax({   
                url: "/Controller/Method",   
                type: "POST",   
                dataType: 'json',   
                contentType: 'application/x-www-form-urlencoded; charset=UTF-8',   
                data: valdata   
            });

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM