Search code examples
sql-serverasp.net-core-mvc-2.0

ASP.NET MVC CORE 2.0 sending data from DOM to SQL Server


I need a strategy here.

In webforms I used a <asp:HiddenField> inside an <asp:UpdatePanel> to send back and forth data from DOM to SQL Server.

The great feature of this approach was to avoid a page refresh (!important)

In ASP.NET MVC CORE 2.0, there is no <asp:UpdatePanel> and I understand I have to send data back and forth from view to controller.

Where do I find a working example, simple enough for a beginner with ASP.NET MVC Core 2.0? I am working on this for a whole long day and so far everything I saw was a ton of samples extremely far more complex than the old <asp:HiddenField> > <asp:UpdatePanel>.


Solution

  • I presume you are wanting to update part of the screen with new information without reloading the whole screen.

    The following jQuery JavaScript code is an example of calling a controller action and returning some data and then stuffing it into a DOM element with a class of result:

       $('#CategoryID').on("change", function () {
            var categoryId = $('#CategoryID').val();
            $.get("/Products/UpdateSubCategories/" + categoryId , function (data) {
                console.log("Data: " + data);
                $('.result').html(data);
            });
        })
    

    This JavaScript fires when the element with an ID of CategoryID changes.

    Here's the example of the controller action:

       [HttpGet]
        public async Task<IActionResult> UpdateSubCategories(int id)
        {
            if (id==0)
            {
                NotFound();
            }
            ViewData["SubCategoryId"] = new SelectList(_context.SubCategories.Where(s => s.CategoryId == id).OrderBy(s => s.SubCategoryName), "Id", "SubCategoryName");
            return PartialView();
    
        }
    

    Note also created a Partial View that is used to create the required HTML for a Select List.

    @model Namespace.Models.Products
    
    
    <div class="form-group">
        <label asp-for="SubCategoryId" class="control-label"></label><span style="color:red"> *</span>
        <select asp-for="SubCategoryId" class="form-control" asp-items="ViewBag.SubCategoryId">
            <option value="">-</option>
        </select>
        <span asp-validation-for="SubCategoryId" class="text-danger"></span>
    </div>