[英]Converting a Model to a JSON object in ASP.NET Core MVC
[英]Save jQuery JSON object into SQL table without creating View model class in MVC ASP.NET Core
我正在從 URL 讀取 JSON 數據並將其插入 SQL 表中。 我使用了這個示例 URL https://raw.githubusercontent.com/wedeploy-examples/supermarket-web-example/master/products.json 並創建了一個 Model ZA2F2ED4F8EBC2CBB4C21A29DDC40AB6 文件如下。
查看 Model Class
public class ApiJsonViewModel
{
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; }
}
我有一個帶有一個文本框控件的表單來顯示來自第三方 API URL 的 JSON 關鍵數據和一個包含數據庫值的下拉列表。
The model class used to populate dropdownlist
public class K360DbCatgViewModel
{
public string Name { get; set; }
public string MetaTitle { get; set; }
public string MetaKeywords { get; set; }
public string MetaDescription { get; set; }
public string ShortDescription { get; set; }
public string Description { get; set; }
public string Specification { get; set; }
public decimal Price { get; set; }
public decimal? OldPrice { get; set; }
public decimal? SpecialPrice { get; set; }
public DateTimeOffset? SpecialPriceStart { get; set; }
public DateTimeOffset? SpecialPriceEnd { get; set; }
public int StockQuantity { get; set; }
public string Sku { get; set; }
public string Gtin { get; set; }
public string NormalizedName { get; set; }
public int DisplayOrder { get; set; }
public int ReviewsCount { get; set; }
public double? RatingAverage { get; set; }
}
Razor 查看頁面
<table class="table" id="tb_properties" style="width:100%">
<tr>
@if (ViewBag.ApiProp != null)
{
@foreach (var itemApiProp in ViewBag.ApiProp)
{
<td>
<input type="text" value="@itemApiProp.Key" class="form-control" />
<select class="form-control">
<option value="">--Select-- </option>
@foreach (var itemK360Prop in ViewBag.K360Prop)
{
<option>@itemK360Prop.Key</option>
}
</select>
</td>
}
}
</tr>
<tr>
<td>
<button type="submit" class="btn btn-primary" style="margin-
right:50px">Catalog Mapping</button>
</td>
</tr>
</table>
Controller 代碼來獲取視圖控件的值
public IActionResult Index()
{
string strAPIUrl = "https://raw.githubusercontent.com/wedeploy-examples/supermarket-web-example/master/products.json";
string jsonUrlProducts;
using (WebClient client = new WebClient())
{
jsonUrlProducts = client.DownloadString(strAPIUrl);
}
CreateDynamicAPiProp(jsonUrlProducts);
CreateK360Prop();
return View();
}
[HttpGet]
public IActionResult CreateDynamicAPiProp(string ApiUrl)
{
Dictionary<string, object> dictResultsAdd = new Dictionary<string, object>();
var objResponseB = JsonConvert.DeserializeObject<List<Dictionary<string, object>>>(ApiUrl);
foreach (Dictionary<string, object> DictMainKV in objResponseB)
{
foreach (KeyValuePair<string, object> item in DictMainKV)
{
dictResultsAdd.Add(item.Key, item.Value);
}
break;
}
ViewBag.ApiProp = dictResultsAdd;
return RedirectToAction("Index");
}
[HttpGet]
public IActionResult CreateK360Prop()
{
var ListK360Prop = new List<ApiMapDbViewModel>();
PropertyInfo[] propertyInfosK360 = typeof(K360DbCatgViewModel).GetProperties();
foreach (PropertyInfo propertyInfoK360 in propertyInfosK360)
{
ListK360Prop.Add(new ApiMapDbViewModel{Value = propertyInfoK360.Name.ToString(), Key = propertyInfoK360.Name.ToString()});
}
ViewBag.K360Prop = ListK360Prop;
return RedirectToAction("Index");
}
I have used the below jQuery and passed the JSON Model object to controller insert method on HTTP post to save selected records.
jQuery代碼
@section scripts{
<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: "/KEMap/Insert",
data: {
jsonModel: jsobject
},
success: function(response) {
toastr.info(response.status + "<br>" + "<br>" + response.message);
$("#tb_properties select").val("");
$("#partial_div").load(window.location.href + " #partial_div");
},
error: function(xhr, textStatus, errorThrown) {
console.log('in error');
}
});
});
});
</script>
插入方法
[HttpPost]
public IActionResult Insert(ApiJsonViewModel jsonModel)
{
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)
{
_context.K360mapMasters.AddRange(K360mapListObj);
_context.SaveChanges();
return Json(new { Status = "Sucess", Message = "Mapped" });
}
return Json(new { Status = "Fail", Message = "Not done" });
}
SQL表
CREATE TABLE [dbo].[K360Map_Master](
[Id] [int] IDENTITY(1,1) NOT NULL,
[ClientCatalog] [nvarchar](450) NOT NULL,
[K360Catalog] [nvarchar](450) NOT NULL,
[MapFlag] [bit] NOT NULL,
CONSTRAINT [PK_K360Map_Master] PRIMARY KEY CLUSTERED
(
[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
一切正常。 我能夠將選定的文本框和下拉列表值插入 SQL 表中。
問題是我使用來自第三方 API URL 的 JSON 數據動態不同。 For example for the below 2 sample URLs, I need to create again 2 model class file.https://gist.githubusercontent.com/dpetersen/1237910/raw/6ceb2161f756d4b4d5c22754d1ed8d869249f186/product_grid.js https://raw.githubusercontent.com/ mdn/fetch-examples/master/fetch-json/products.json 。
我得到的反饋是帶有 static 數據的硬編碼編碼。 我不允許為每個 URL 創建單獨的 model class。
如果不創建 model class 文件,我也不知道如何繼續。 我需要將選定的控制值傳遞給沒有 JSON model ZA8CFDE63319446B8 的 controller 插入方法。
我希望有人可以在這里幫助我。
這是您可以遵循的工作演示:
Model:
public class ApiMapDbViewModel
{
public string Value { get; set; }
public string Key { get; set; }
}
public class K360mapMaster
{
public string ClientCatalog { get; set; }
public string K360catalog { get; set; }
}
public class K360DbCatgViewModel
{
public string AA { get; set; }
public string BB { get; set; }
public string CC { get; set; }
public string DD { get; set; }
}
看法:
<table class="table" id="tb_properties" style="width:100%">
<tr>
@if (ViewBag.ApiProp != null)
{
@foreach (var itemApiProp in ViewBag.ApiProp)
{
<td>
<input type="text" value="@itemApiProp.Key" class="form-control" />
<select class="form-control">
<option value="">--Select-- </option>
@foreach (var itemK360Prop in ViewBag.K360Prop)
{
<option>@itemK360Prop.Key</option>
}
</select>
</td>
}
}
</tr>
<tr>
<td>
<button type="submit" class="btn btn-primary" style="margin-
right:50px">
Catalog Mapping
</button>
</td>
</tr>
</table>
JS(添加data: jsonstr,contentType:"application/json"
):
@section scripts{
<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: "/KEMap/Insert",
//data: jsobject,
data: jsonstr,
contentType:"application/json",
success: function (response) {
toastr.info(response.status + "<br>" + "<br>" + response.message);
$("#tb_properties select").val("");
$("#partial_div").load(window.location.href + " #partial_div");
},
error: function (xhr, textStatus, errorThrown) {
console.log('in error');
}
});
});
});
</script>
}
Controller:
[HttpPost]
public IActionResult Insert([FromBody]JObject jsonModel)
{
Type type = jsonModel.GetType();
PropertyInfo[] props = type.GetProperties();
List<K360mapMaster> K360mapListObj = new List<K360mapMaster>();
foreach (JProperty prop in jsonModel.Children())
{
string key = prop.Name.ToString();
string value = prop.Value.ToString();
K360mapListObj.Add(new K360mapMaster() { ClientCatalog = key, K360catalog = value });
}
//do your stuff...
return Json(new { Status = "Fail", Message = "Not done" });
}
注1 :
因為ApiJsonViewModel
中的mapped屬性首字母大寫,所以這里得到的數據ClientCatalog = c.Name,
是大寫。從我提供的代碼來看,這里的代碼string key = prop.Name.ToString();
獲取小寫的json( https://raw.githubusercontent.com/wedeploy-examples/supermarket-web-example/master/products.json
)鍵名。如果你想保留第一個字母大寫,你可以改變以下行:
string key = prop.Name.ToString().First().ToString().ToUpper() + prop.Name.ToString().Substring(1);
注2 :
如果您的項目是asp.net core 3.x 或 asp.net 5 ,請確保您的項目有Newtonsoft 支持,否則您無法成功將數據傳遞到后端。更多詳細信息您可以參考:
.NET 5.0 MVC 返回 Json 正在拋出 JSON 解析器錯誤
結果:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.