C# Jquery/Ajax更新表[ASP.NET核心MVC]
我不确定在使用AJAX Jquery之后如何刷新表数据 我需要帮助。我有一个razor视图,在按钮上单击按钮,我发送带有文本框的post请求,并下拉选择值,然后在控制器中,为toastr传递Json响应状态 下一个控制器返回视图并正确显示烤面包机状态 主要问题是,我不知道如何在toastr响应状态之后用新插入的记录刷新该表 这是我对控制器的看法:C# Jquery/Ajax更新表[ASP.NET核心MVC],c#,jquery,asp.net-core,razor,asp.net-core-mvc,C#,Jquery,Asp.net Core,Razor,Asp.net Core Mvc,我不确定在使用AJAX Jquery之后如何刷新表数据 我需要帮助。我有一个razor视图,在按钮上单击按钮,我发送带有文本框的post请求,并下拉选择值,然后在控制器中,为toastr传递Json响应状态 下一个控制器返回视图并正确显示烤面包机状态 主要问题是,我不知道如何在toastr响应状态之后用新插入的记录刷新该表 这是我对控制器的看法: @using SimplCommerce.WebHost.Models @model dynamic public IActionResult I
@using SimplCommerce.WebHost.Models @model dynamic
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." });
}
}
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");
}
}
@if(Model.dynmappedatamodel!=null)
{
@foreach (K360mapMaster itemMappedData in Model.dynMappedDataModel)
{
<tr>
<td>@itemMappedData.ClientCatalog</td>
<td>@itemMappedData.K360catalog</td>
</tr>
}
}
您可以使用JQuery循环遍历
元素,并使用JQuery选择器获取属性名称和所选值。然后,根据该值生成一个JS对象,并使用jqueryajax调用controller动作方法,将该对象存储到数据库中
请参考以下示例代码:
型号:
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; }
}
控制器:
@using SimplCommerce.WebHost.Models @model dynamic
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." });
}
}
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");
}
}
结果如下:
问题现已解决
为部分视图中的表提供了id
并在jquerysuces函数下面添加了一段代码
$("#par_tbl").load(window.location.href + " #par_tbl");
$(“#par#tbl”).load(window.location.href+“#par#tbl”) 非常感谢你的支持。我会调查一下,然后尽快给你回复,一切正常,除了。我需要在sep表中插入两个字段,这是我的旧代码@{var K360list=new SelectList((System.Collections.IEnumerable)ViewData[“K360DbPropVD”],“Value”,“Key”);}
@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>
}
[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");
}
public class ApplicationDbContext : IdentityDbContext
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options)
{
}
public DbSet<K360Master> K360Master { get; set; }
}
[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");
}
[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" });
}
}
//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');
}
});