Create view - Pass parameter and update model vie Stored Procedure

EB 1 Reputation point
2021-09-27T15:51:41.083+00:00

How would I pass a parameter from a view, run a stored procedure and update specific model values on the same view, then be able to change those values if needed and save them.

EB

ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,383 questions
{count} votes

1 answer

Sort by: Most helpful
  1. Zhi Lv - MSFT 32,091 Reputation points Microsoft Vendor
    2021-09-28T05:29:24.097+00:00

    Hi @EB ,

    How would I pass a parameter from a view, run a stored procedure and update specific model values on the same view, then be able to change those values if needed and save them.

    To pass parameter from view to the controller and update the model on the same view, you could try to use the partial view and JQuery Ajax.

    Please refer the following sample, in this sample, we will use a StudentIndex partial view to display the student list and use an EditStudent partial view to update the selected student. And we will use JQuery ajax to load the partial view dynamically.

    Partial view: StudentIndex.cshtml

    @model IEnumerable<MVCWebApplication.Data.Student>  
       
    <table class="table">  
        <thead>  
            <tr>  
                <th>  
                    @Html.DisplayNameFor(model => model.Name)  
                </th>  
                <th>  
                    @Html.DisplayNameFor(model => model.GradeId)  
                </th>  
                <th></th>  
            </tr>  
        </thead>  
        <tbody>  
            @foreach (var item in Model)  
            {  
                <tr>  
                    <td>  
                        @Html.DisplayFor(modelItem => item.Name)  
                    </td>  
                    <td>  
                        @Html.DisplayFor(modelItem => item.GradeId)  
                    </td>  
                    <td>  
                        <a id ="@item.Id" href="#" class = "btnEdit"> Edit</a>  
                    </td>  
                </tr>  
            }  
        </tbody>  
    </table>  
    

    Partial view: EditStudent.cshtml

    @model MVCWebApplication.Data.Student  
       
    <div class="row">  
        <div class="col-md-4">  
            <form asp-action="EditStudent">  
                <div asp-validation-summary="ModelOnly" class="text-danger"></div>   
                <div class="form-group">  
                    <label asp-for="Name" class="control-label"></label>  
                    <input asp-for="Name" class="form-control " id="txtname"/>  
                    <span asp-validation-for="Name" class="text-danger"></span>  
                </div>  
                <div class="form-group">  
                    <label asp-for="GradeId" class="control-label"></label>  
                    <input asp-for="GradeId" class="form-control " id="txtgradeId" />  
                    <span asp-validation-for="GradeId" class="text-danger"></span>  
                </div>  
                <div class="form-group">  
                    <input type="button" value="Save" class="btn btn-primary " id="btnUpdate" data-id="@Model.Id" />  
                </div>  
            </form>  
        </div>  
    </div>   
      
    @section Scripts {  
        @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}  
    }  
    

    Main page: Index.cshtml:

    @model IEnumerable<MVCWebApplication.Data.Student>  
      
    @{  
        ViewData["Title"] = "Index";  
        Layout = "~/Views/Shared/_Layout.cshtml";  
    }  
      
    <h1>Index</h1>  
      
    <p>   
        <a asp-action="Create">Create New</a>  
    </p>  
    <div id="divIndex">  
        @*display the student list*@  
        <partial name="StudentIndex" data="@Model"/>  
    </div>  
      
    <div id="editcontainer">  
        @*display the update student*@   
    </div>  
    
    @section Scripts{   
    < script type="text/javascript" >  
        $(function () {  
            $(".btnEdit").each(function (index, item) {  
                $(item).click(function () {  
                    event.preventDefault();  
                    //get the edit user primary key.  
                    var id = $(this).attr("id");  
                    $.ajax({  
                        url: "/Students/EditStudent",  
                        method: "Get",  
                        data: { "id": id },  
                        success: function (response) {  
                            //update the update student panel  
                            $("#editcontainer").html("");  
                            $("#editcontainer").html(response);  
      
                            $("#btnUpdate").click(function () {  
      
                                //get the updated student information  
                                var student = {};  
                                student.id = $(this).attr("data-id");  
                                student.name = $("#txtname").val();  
                                student.gradeId = $("#txtgradeId").val();  
                                $.ajax({  
                                    url: "/Students/EditStudent",  
                                    method: "Post",  
                                    data: { "student": student },  
                                    success: function (response) {  
      
                                        //update the student list panel  
                                        $("#divIndex").html("");  
                                        $("#divIndex").html(response);  
                                    }  
                                })  
      
                            });  
                        }  
                    })  
                });  
            })   
        });  
    < /script >  
    }  
    

    Students Controller:

    public class StudentsController : Controller  
    {  
        private readonly ApplicationDbContext _context;  
        public StudentsController(ApplicationDbContext dbContext)  
        {  
            _context = dbContext;  
        }  
        public IActionResult Index()  
        {  
            return View(_context.Students.ToList());  
        }  
           
        public IActionResult EditStudent(int id)  
        {  
            if(id == 0)  
            {  
                throw new NullReferenceException();  
            }  
            var student = _context.Students.Where(c => c.Id == id).FirstOrDefault();  
    
            return PartialView("EditStudent",student);  
        }  
    
        [HttpPost]  
        public IActionResult EditStudent(Student student)  
        {  
            if (!ModelState.IsValid)  
            {  
                return Ok("Model invalid");  
            }  
            //you can change the following code and update the model via stored procedure.  
            var stu = _context.Students.Where(c => c.Id == student.Id).FirstOrDefault();  
            stu.Name = student.Name;  
    
            _context.SaveChanges();  
            return PartialView("StudentIndex", _context.Students.ToList());  
        }  
    }  
    

    The result as below:

    135726-1.gif

    Then, to update the model via stored procedure, you could refer the following tutorials:

    Working with Stored Procedure in Entity Framework Core

    Entity Framework Core Stored Procedure


    If the answer is helpful, please click "Accept Answer" and upvote it.
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    Best regards,
    Dillion

    0 comments No comments