[英]Send Model With Json In Asp.net Core
我想將模型從控制器傳遞給 View 中的Success方法,並使用 json 訪問模型中的屬性。 如何編寫以及如何訪問Success方法中的屬性?
public async Task<IActionResult> Edit( Department department)
{
if (ModelState.IsValid)
{
_genericRepository.Update(department);
await _genericRepository.SaveChangesAsync();
var model = _genericRepository.GetByIdAsync(department.Department_Id);
return Json(new { Message = model });
}
return Json(department);
}
<script> function Success(data) { alert(data.Messge); } function Failure() { } </script>
怎么樣:
$.ajax({
url: "<path>/Edit",
type: "POST",
data: JSON.stringify(department),
dataType: "json",
cache: false,
success: function (data) {
[...]
},
error: function () {
[...]
}
})
使用Json.Parse();
時,您可以從 json 文件訪問data list
Json.Parse();
<script>
function Success(data)
{
var getDataList = Json.parse(data);
alert(getDataList);
}
function Failure() {
}
</script>
public ActionResult Import()
{
string response = JsonConvert.SerializeObject(responseModel);
return this.Content(response);
}
class ResponseModel
{
public string bodyone { get; set; }
public string bodytwo { get; set; }
public string HeadersFile1 { get; set; }
public string HeadersFile2 { get; set; }
public string FileName1 { get; set; }
public string FileName2 { get; set; }
}
然后使用 JSON 解析器解析響應。 現在您可以像這樣從 ajax 成功讀取屬性值
success: function (response) {
if (response.length == 0)
alert('Some error occured while uploading');
else {
var obj = JSON.parse(response);
$('#divPrint').html(obj.bodyone);
$('#divPrint2').html(obj.bodytwo);
$('#fileName1').html(obj.FileName1);
$('#fileName2').html(obj.FileName2);
$('#headersFile1').html(obj.HeadersFile1);
$('#headersFile2').html(obj.HeadersFile2);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.