简体   繁体   English

Jquery/Ajax 更新表[ASP.NET Core MVC]

[英]Jquery/Ajax to update a TABLE[ASP.NET Core MVC]

I'm not sure how to refresh table data after I use AJAX Jquery.我不确定在使用 AJAX Jquery 后如何刷新表数据。

i need an help.我需要帮助。 i've a razor view, on button click button I am sending post request with textbox and dropdown selected values, then in controller, passed Json response status for toastr.我有一个 razor 视图,在按钮单击按钮上我发送带有文本框和下拉选择值的发布请求,然后在 controller 中,将 Json 响应传递给状态。

Next controller returns a view and display toaster status correctly.接下来 controller 返回视图并正确显示烤面包机状态。

The main problem is that I dont know how to refresh that table with newly inserted records after toastr response status.主要问题是我不知道如何在 toastr 响应状态后用新插入的记录刷新该表。

This is my view of the Controller:这是我对 Controller 的看法:

@using SimplCommerce.WebHost.Models @model dynamic
    <table id="tbl_btn">
        <tr>
            <td align="center">
                <button type="submit">Catalog Mapping</button>
            </td>
        </tr>
    </table>

    <table id="tb_properties" style="width:100%">
        <tr>
            @foreach (ApiMapDbViewModel itemApiProp in Model.dynApiPropModel)
            {
                <td>
                    <input type="text" value="@itemApiProp.Key" readonly="readonly" />
                    <hr />

                    <select>
                        <option value="">-Select-</option>
                        @foreach (ApiMapDbViewModel itemK360Prop in Model.dynK360PropModel)
                        {
                            <option>@itemK360Prop.Key</option>

                        }
                    </select>
                </td>
            }
        </tr>
    </table>

    <div id="partial_div">
        @Html.Partial("KPartialIndex")
    </div>

</form>

@section scripts{ @section 脚本{

<script>
    $(function () {
        $("button[type='submit']").click(function () {
            event.preventDefault();
            var properties = [];
            $("#tb_properties tr:first").find("td").each(function (index, item) {
                var propertyname = $(item).find("input[type='text']").val();
                var selctedvalue = $(item).find("select").val();
                properties.push('"' + propertyname + '":"' + selctedvalue + '"');
            });
            var jsonstr = '{' + properties.join(",") + '}';
            var jsobject = JSON.parse(jsonstr);

            $.ajax({
                type: "Post",
                url: "/KMap/Insert",
                data: { jsonModel: jsobject },
                success: function (response) {
                    toastr.error(response.status + "----->" + response.message);
                    //info//warning//error//success
                    toastr.options = {
                        "closeButton": false,
                        "debug": false,
                        "newestOnTop": false,
                        "progressBar": false,
                        "positionClass": "toast-top-center",
                        "preventDuplicates": false,
                        "onclick": null,
                        "showDuration": "1000",
                        "hideDuration": "1000",
                        "timeOut": "5000",
                        "extendedTimeOut": "1000",
                        "showEasing": "swing",
                        "hideEasing": "linear",
                        "showMethod": "fadeIn",
                        "hideMethod": "fadeOut"
                    };

                    $("#map_Form select").val("");
                    $("#partial_div").load("/KMap/LoadPartialViewOnPost"); // not working

                },
                error: function (xhr, textStatus, errorThrown) {
                    console.log('in error');
                }
            });
        });
    });

</script>

} }

This is my partial view:这是我的部分观点:

@using SimplCommerce.WebHost.Models @model dynamic
@if (Model.dynMappedDataModel != null) @if (Model.dynMappedDataModel != null)
 public IActionResult Index()
    {
        dynamic dynModel = new ExpandoObject();
        dynModel.dynApiPropModel = GetListApiProp();
        dynModel.dynMappedDataModel = ListMappedData();
        dynModel.dynK360PropModel = GetListK360Prop();
        return View(dynModel);
    }

    [HttpPost]
    public IActionResult LoadPartialViewOnPost()
    {
        dynamic mymodel = new ExpandoObject();
        mymodel.dynMappedDataModel = ListMappedData();
        return PartialView("KPartialIndex", mymodel);
    }

    public List<K360mapMaster> ListMappedData()
    {
        List<K360mapMaster> items = new List<K360mapMaster>();
        var query = from K360mapMaster in _context.K360mapMasters
                    select K360mapMaster;
        var mappings = query.ToList();
        foreach (var mappingData in mappings)
        {
            items.Add(new K360mapMaster()
            {
               
                ClientCatalog = mappingData.ClientCatalog,
                K360catalog = mappingData.K360catalog

            });
        }
        return items;
    }

    [HttpPost]
    [ValidateAntiForgeryToken]
    public IActionResult Insert(ApiJsonViewModel jsonModel)
    {
        if (!ModelState.IsValid)
        {
            var errors = ModelState.SelectMany(x => x.Value.Errors, (y, z) => z.Exception.Message);
            return BadRequest(errors);
        }
        Type type = jsonModel.GetType();
        PropertyInfo[] props = type.GetProperties();
        List<K360mapMaster> K360mapListObj = new List<K360mapMaster>();

        K360mapListObj = props.Where(c => !string.IsNullOrEmpty(c.GetValue(jsonModel, null)?.ToString()))
                                        .Select(c => new K360mapMaster() { ClientCatalog = c.Name, K360catalog = c.GetValue(jsonModel, null)?.ToString() })
                                        .ToList();
        if (K360mapListObj.Count > 0)
        {
            try
            {
                var ListCatalogs = K360mapListObj.Select(l => l.ClientCatalog).ToList();

                foreach (var item in ListCatalogs)
                {
                    var DbCatalogs = (from p in _context.K360mapMasters
                                      where p.ClientCatalog == item
                                      select p).FirstOrDefault();
                    if (DbCatalogs != null)
                    {

                        return Json(new { Status = "This is an information notification provided by K360 eCommerce. ", Message = "Selected catalog  " + item + "  already mapped." });
                    }
                }
                _context.K360mapMasters.AddRange(K360mapListObj);
                _context.SaveChanges();                   
               return Json(new { Status = "This is a success notification from K360 eCommerce. ", Message = "Product catalog's mapped sucessfully." });
            }
            catch
            {
                return Json(new { Status = "This is an error notification provided by K360 eCommerce. ", Message = "Mapping failed" });
            }
        }
        else
        {
            return Json(new { Status = "This is a warning notification provided by K360 eCommerce. ", Message = "No product catalog selected." });
        }

    }

This is my controller:这是我的 controller:

 public IActionResult Index() { dynamic dynModel = new ExpandoObject(); dynModel.dynApiPropModel = GetListApiProp(); dynModel.dynMappedDataModel = ListMappedData(); dynModel.dynK360PropModel = GetListK360Prop(); return View(dynModel); } [HttpPost] public IActionResult LoadPartialViewOnPost() { dynamic mymodel = new ExpandoObject(); mymodel.dynMappedDataModel = ListMappedData(); return PartialView("KPartialIndex", mymodel); } public List<K360mapMaster> ListMappedData() { List<K360mapMaster> items = new List<K360mapMaster>(); var query = from K360mapMaster in _context.K360mapMasters select K360mapMaster; var mappings = query.ToList(); foreach (var mappingData in mappings) { items.Add(new K360mapMaster() { ClientCatalog = mappingData.ClientCatalog, K360catalog = mappingData.K360catalog }); } return items; } [HttpPost] [ValidateAntiForgeryToken] public IActionResult Insert(ApiJsonViewModel jsonModel) { if (.ModelState.IsValid) { var errors = ModelState.SelectMany(x => x.Value,Errors, (y. z) => z.Exception;Message); return BadRequest(errors). } Type type = jsonModel;GetType(). PropertyInfo[] props = type;GetProperties(); List<K360mapMaster> K360mapListObj = new List<K360mapMaster>(). K360mapListObj = props.Where(c =>.string,IsNullOrEmpty(c?GetValue(jsonModel. null)..ToString())),Select(c => new K360mapMaster() { ClientCatalog = c.Name, K360catalog = c?GetValue(jsonModel. null).;ToString() }).ToList(). if (K360mapListObj.Count > 0) { try { var ListCatalogs = K360mapListObj.Select(l => l;ClientCatalog).ToList(). foreach (var item in ListCatalogs) { var DbCatalogs = (from p in _context.K360mapMasters where p;ClientCatalog == item select p).FirstOrDefault(), if (DbCatalogs.= null) { return Json(new { Status = "This is an information notification provided by K360 eCommerce; ". Message = "Selected catalog " + item + " already mapped." }); } } _context.K360mapMasters;AddRange(K360mapListObj). _context,SaveChanges(). return Json(new { Status = "This is a success notification from K360 eCommerce; ". Message = "Product catalog's mapped sucessfully," }); } catch { return Json(new { Status = "This is an error notification provided by K360 eCommerce. ", Message = "Mapping failed" }). } } else { return Json(new { Status = "This is a warning notification provided by K360 eCommerce; ", Message = "No product catalog selected." }); } }

I want to refresh the new insert records after toastr response status.Please HelpThanks我想在 toastr 响应状态后刷新新的插入记录。请帮助谢谢

Issue is fixed now.问题现已修复。

Provided id for the table in partial view.为部分视图中的表提供了 ID。

and in Jquery Sucess function addded below piece of code并在 Jquery Sucess function 中添加了以下代码

 $("#par_tbl").load(window.location.href + " #par_tbl");

You could use JQuery to loop through the <td> elements, and use JQuery Selector gets the property name and selected value.您可以使用 JQuery 循环遍历<td>元素,并使用 JQuery 选择器获取属性名称和选定值。 Then, according to the value to generate a JS object, and use JQuery Ajax to call the controller action method and store the object into the database. Then, according to the value to generate a JS object, and use JQuery Ajax to call the controller action method and store the object into the database.

Please refer the following sample code:请参考以下示例代码:

Models:楷模:

public class SMJsonModel
{
    public string title { get; set; }
    public string type { get; set; }
    public string description { get; set; }
    public string fileName { get; set; }
    public string height { get; set; }
    public string width { get; set; }
    public string price { get; set; }
    public string rating { get; set; }
}
public class PropertyInfoK360
{
    public string Value { get; set; }
    public string Key { get; set; }
}

Controller: Controller:

public class SupermarketController : Controller
{
    public IActionResult Index()
    {
        //initial data:
        List<SMJsonModel> JsonResultList = new List<SMJsonModel>()
        {
            new SMJsonModel(){
                title="Brown eggs",
                type="dairy",
                description="Raw organic brown eggs in a basket",
                fileName="0.jpg",
                height = "600",
                width="400",
                price="28.1",
                rating="4"
            }
        };
        ViewData["K360DbPropVD"] = new List<PropertyInfoK360>()
        {
            new PropertyInfoK360(){ Value="AAA", Key="AAA"},
             new PropertyInfoK360(){ Value="BBB", Key="BBB"},
              new PropertyInfoK360(){ Value="CCC", Key="CCC"},
               new PropertyInfoK360(){ Value="DDD", Key="DDD"},
                new PropertyInfoK360(){ Value="EEE", Key="EEE"},
                 new PropertyInfoK360(){ Value="FFF", Key="FFF"},
                  new PropertyInfoK360(){ Value="GGG", Key="GGG"},
        };
        return View(JsonResultList);
    }
    // this method is used to insert data into database.
    [HttpPost]
    public IActionResult Insert(SMJsonModel jsonModel)
    {
        //insert object into database.

        return Ok("success");
    }
}

Index View page:索引视图页面:

@model IEnumerable<netcore5.Models.SMJsonModel> 
<div class="container">
    <table class="table table-striped table-bordered" id="tb_properties" style="width:100%">
        <thead>
        </thead>
        <tbody>
            <tr>
                @foreach (var property in Model.GetType().GetGenericArguments()[0].GetProperties())
                {
                    <td>
                        <input type="text" value="@property.Name" class="form-control" />
                        @{var K360list = new SelectList((System.Collections.IEnumerable)ViewData["K360DbPropVD"], "Value", "Key");}
                        <select asp-items="K360list" class="form-control"></select>

                    </td>
                }
            </tr>
        </tbody>
    </table>
</div>
<div class="container">
    <table class="table table-striped table-bordered" style="width:100%">
        <tr>
            <td align="center">
                <button type="submit" class="btn btn-primary">Catalog Mapping</button>
            </td>
        </tr>
    </table>
</div>

@section scripts{
<script>
    $(function () {
        $("button[type='submit']").click(function () {
            event.preventDefault();
            var properties = []; //define an array to store the property name and the selected value.
            $("#tb_properties tr:first").find("td").each(function (index, item) {
                var propertyname = $(item).find("input[type='text']").val();
                var selctedvalue = $(item).find("select").val(); 
                properties.push('"' + propertyname + '":"' + selctedvalue + '"');
            }); 
            //According the properties to genereate the json string.
            var jsonstr = '{' + properties.join(",") + '}';
            //convert the json string to js object.
            var jsobject = JSON.parse(jsonstr);
            //call the Inset method and store data into the database.
            $.ajax({
                type: "Post",
                url: "/Supermarket/Insert",
                data: { jsonModel: jsobject },
                success: function (response) {
                    console.log(response); 

                },
                error: function (xhr, textStatus, errorThrown) {
                    console.log('in error');
                }
            });
        });
    });
</script>
}

The screenshot as below:截图如下:

在此处输入图像描述

Update更新

As mentioned in the comment, to store the JsModel's property name as the first column and its value as the second column's value in the K360ECommerceS table, you could refer the following code:如评论中所述,要将 JsModel 的属性名称存储为 K360ECommerceS 表中的第一列并将其值存储为第二列的值,您可以参考以下代码:

    [HttpPost]
    public IActionResult Insert(SMJsonModel jsonModel)
    {
        //insert object into database.
        //required using System.Reflection; 
        //use GetType() and GetProperties() method to get object's property name and its value.
        Type type = jsonModel.GetType();
        PropertyInfo[] props = type.GetProperties();

        List<K360Master> k360Masters = new List<K360Master>(); 
        foreach(var item in props)
        {
            K360Master master = new K360Master()
            {
                ClientCatalog = item.Name,
                K360catalog = item.GetValue(jsonModel, null)?.ToString()
            };
            k360Masters.Add(master);
        }
        _context.K360Master.AddRange(k360Masters);
        _context.SaveChanges();
        
        return Ok("success");
    }

After that, the result in the K360Master table as below:之后,K360Master 表中的结果如下:

在此处输入图像描述

[Note] In the above sample, my DBContext as below, it will insert data into the K360Master table, please check your code and make sure you are using the correct Entity and Tables. [注意] 在上面的示例中,我的 DBContext 如下所示,它将向 K360Master 表中插入数据,请检查您的代码并确保您使用了正确的实体和表。

public class ApplicationDbContext : IdentityDbContext
{
    public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
        : base(options)
    {
    }

    public DbSet<K360Master> K360Master { get; set; }
}

Update更新

Only if we select all the 8 dropdownlist then only it gets inserted.只有当我们 select 所有 8 个下拉列表时,才会插入它。 Not able to select only 2 or 3 dropdownlist and it shows Cannot insert the value NULL into column 'K360Catalog'.无法 select 仅 2 或 3 个下拉列表,它显示无法将值 NULL 插入“K360Catalog”列。 Its not null column.它不是 null 列。 please guide me.请指导我。 task needs to finished by today eod任务需要在今天之前完成

In the Insert method, you could check whether the value is null or not before save them to database.在 Insert 方法中,您可以在将它们保存到数据库之前检查值是否为 null。 Code as below:代码如下:

    [HttpPost]
    public IActionResult Insert(SMJsonModel jsonModel)
    {
        //insert object into database.

        Type type = jsonModel.GetType();
        PropertyInfo[] props = type.GetProperties();

        List<K360Master> k360Masters = new List<K360Master>(); 
        foreach(var item in props)
        {
            //check if the value is null or not.
            if(!string.IsNullOrEmpty(item.GetValue(jsonModel, null)?.ToString()))
            {
                K360Master master = new K360Master()
                {
                    ClientCatalog = item.Name,
                    K360catalog = item.GetValue(jsonModel, null)?.ToString()
                };
                // if the value is not null, add it to the list
                k360Masters.Add(master);
            }
        }
        //insert the list items into database.
        _context.K360Master.AddRange(k360Masters);
        _context.SaveChanges();
        
        return Ok("success");
    }

The screenshot as below:截图如下:

在此处输入图像描述

Update更新

From your description, if you don't want to use for each statement to loop through the 8 fields, you could try to use LINQ where clause to filter the data.根据您的描述,如果您不想使用 for 每个语句循环遍历 8 个字段,您可以尝试使用 LINQ where 子句过滤数据。 And, if you want to return multiple value from controller action method to the Ajax function, you could refer a Json result.而且,如果您想从 controller 操作方法返回多个值到 Ajax function,您可以参考 ZEED163385B84088856C 结果。 please check the following sample:请检查以下示例:

    [HttpPost]
    public IActionResult Insert(SMJsonModel jsonModel)
    {
        //insert object into database.

        Type type = jsonModel.GetType();
        PropertyInfo[] props = type.GetProperties();

        List<K360Master> k360Masters = new List<K360Master>(); 
        //using where clause to filter data.
        k360Masters = props.Where(c => !string.IsNullOrEmpty(c.GetValue(jsonModel, null)?.ToString()))
                                        .Select(c=> new K360Master() { ClientCatalog= c.Name,  K360catalog = c.GetValue(jsonModel, null)?.ToString() })
                                        .ToList(); 
        if(k360Masters.Count > 0)
        {
            try
            {
                //foreach (var item in props)
                //{
                //    //check if the value is null or not. if the value is not null, add it to the list
                //    if (!string.IsNullOrEmpty(item.GetValue(jsonModel, null)?.ToString()))
                //    {
                //        K360Master master = new K360Master()
                //        {
                //            ClientCatalog = item.Name,
                //            K360catalog = item.GetValue(jsonModel, null)?.ToString()
                //        };
                //        k360Masters.Add(master);
                //    }
                //}

                _context.K360Master.AddRange(k360Masters);
                _context.SaveChanges();

                return Json(new { Status = "Success", Message = "Insert Success!" }); 
            }
            catch (Exception)
            {
                return Json(new { Status = "Error", Message = "Fail to insert data into database" });
            }
        }
        else
        {
            return Json(new { Status = "Warning", Message = "No selected item" });
        }
    }

Ajax code: Ajax 代码:

        //According the properties to genereate the json string.
        var jsonstr = '{' + properties.join(",") + '}';
        //convert the json string to js object.
        var jsobject = JSON.parse(jsonstr);
        $.ajax({
            type: "Post",
            url: "/Supermarket/Insert",
            data: { jsonModel: jsobject },
            success: function (response) {
                alert(response.status + "--" + response.message);
                //then, based on the status to choose 
            },
            error: function (xhr, textStatus, errorThrown) {
                console.log('in error');
            }
        });

The result like this:结果是这样的:

在此处输入图像描述

Issue is fixed now.问题现已修复。

Provided id for the table in partial view.为部分视图中的表提供了 ID。

and in Jquery Sucess function added below piece of code并在 Jquery Sucess function 中添加了以下代码

$("#par_tbl").load(window.location.href + " #par_tbl"); $("#par_tbl").load(window.location.href + "#par_tbl");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在ASP.NET MVC中使用Ajax更新 - Update using ajax in asp.net mvc Asp.net核心MVC和JQuery提交 - Asp.net core MVC and JQuery submit 在一个表中创建记录将更新另一个表中的现有记录 ASP.NET Core MVC - Creating a record in one table will update an existing record in another table ASP.NET Core MVC 如何在我的 ASP.NET Core MVC 项目中引用 Microsoft.JQuery.Unobtrusive.Ajax - How to reference Microsoft.JQuery.Unobtrusive.Ajax within my ASP.NET Core MVC project 在 ASP.NET Core MVC 应用程序中使用 ajax JQuery 呈现后,JSON 数据返回为未定义 - JSON data is returned as undefined after rendered using ajax JQuery in ASP.NET Core MVC app 如何在 ASP.NET Core MVC 中,在 AJAX 调用中动态创建的表上添加分页 - How to add pagination in ASP.NET Core MVC, on dynamically created table within AJAX call 如何在ASP.NET Core MVC中更新这种类型的关系表数据 - How to update this type of relationship table data in ASP.NET Core MVC 将模型添加到单独的表时,ASP.NET MVC AJAX更新选择列表项 - ASP.NET MVC AJAX Update select list items when model is added to separate table 如何在C#ASP.NET MVC项目中使用ajax更新SQL表中的记录顺序? - How to update orders of records in SQL table using ajax in C# ASP.NET MVC project? 使用 Ajax 过滤模型更新 foreach 循环中的表(asp.net mvc c#) - Update table in foreach loop with filtered model with Ajax (asp.net mvc c#)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM