简体   繁体   中英

Retrieving Data From Database and Inserting to Textbox Using ASP.NET MVC

I have a view, in the view, I have a section where you can enter the customer account number and then press search

I want the search to query the SQLSERVER for the account number details and retrieve the other details like Name, Account Balance and the likes.

I have finished the View code but I am confused on how to implement the Controller and whether I should use AJAX to ensure that the page does not reload.

Could you advise me?

Below is the View.

@model CreditFacility_Web.Models.CreditFacilityModel.Transaction
@{
Layout  = "~/Views/Shared/_Layout.cshtml";
}

   <div class="w3-container" style="padding-left:60px">
   @{
      ViewBag.Title = "Credit Transaction";
   }

@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()

<div class="form-horizontal">
    <h2>Credit Transaction</h2>
    <hr />
    @Html.ValidationSummary(true, "", new { @class = "text-danger" })
    <div class="form-group">
        @Html.LabelFor(model => model.Account_Number, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.Account_Number, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.Account_Number, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        <div class="col-md-offset-2 col-md-10">
            <button  value="Search" class="btn btn-primary" >Search</button>
        </div>
    </div>

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

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

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

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

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

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

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

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

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

    <div class="form-group">
        <div class="col-md-offset-2 col-md-10">
            <input type="submit" value="Create" class="btn btn-success" />
        </div>
    </div>
</div>
}

<div>
    @Html.ActionLink("Back to List", "Index")
</div>

I have been able to work on the View and the Controller and below is what i have.

@section Scripts {

<script type="text/javascript">
$(document).ready(function () {
$(".btn-primary").click(function () {
var accNo = $('#Account_Number').val();

$.ajax({
        url: "@Url.Action("AccountDetails", "Transactions")",
        type: "POST",
        dataType: "json",
        data: { accountNo : accNo },
        async: false,

    error: function () {
        alert('Account Number do not Exist Or Other Errors Occurred');
        },

        success: function (data) {
        if (Object.keys(data).length > 0) {
        $('#Firstname').val(data.Firstname);
        $('#Old_Balance').val(data.Account_Balance);
        }
        }
        });
 });
 });

</script>

}

And the Controller has the below.

  [HttpPost]
      public ActionResult AccountDetails(string accountNo)
    {
        using (var db = new CreditFacilityContext())
        {

            var accDetails = db.SavingsAccounts.Where(t => t.Account_Number == accountNo).Select(s => new SavingsAccount
            {
                Firstname = s.Firstname,
                Account_Balance = s.Account_Balance,
                //rest of properties                    
            }).FirstOrDefault(); ;

            return Json(accDetails, JsonRequestBehavior.AllowGet);
        }

        
    }

Ajax method to retrieve data without page refresh:

$(".btn-primary").click(function () {
    var accNo = $('#Account_Number').val();
   
    $.ajax({
            url: "@Url.Action("AccountDetails", "Home")",
            type: "POST",
            dataType: "json",
            data: { accountNo : accNo },
            async: false,

            error: function () {
            },

            success: function (data) {
            if (Object.keys(data).length > 0) {
                $('#Firstname').val(data.FirstName);
                $('#Old_Balance').val(data.Balance);
               }
            }
    });
 });

Home Controller code to fetch data from SQL Server:

 [HttpPost]
 public JsonResult AccountDetails(string accountNo)
 {
    using (DBContextModel dataContext = new DBContextModel())
    {
       var accSearchParameter = new SqlParameter("@Search", accountNo);
       var accDetails = dataContext.Database.SqlQuery<AccDetails>("EXEC YourStoredProc @Search", accSearchParameter ).Select(s => new AccDetails
        {
           FirstName = s.FirstName,
           Balance = s.Balance,
           //rest of properties                    
        }).SingleOrDefault();
        return Json(accDetails, JsonRequestBehavior.AllowGet);
     }
 }

Pre-requisites for the Controller code to work:

  1. Stored procedure
  2. AccDetails class with properties that match the select column names/aliases of SP. Try this, I think you probably need to read up on jQuery Ajax and JSON in MVC.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM