简体   繁体   English

在 Asp.net Core 中使用 Json 发送模型

[英]Send Model With Json In Asp.net Core

I want to pass the model from controller to Success method in View and access the properties from the model with json.我想将模型从控制器传递给 View 中的Success方法,并使用 json 访问模型中的属性。 How do I write and how to access the properties in Success method?如何编写以及如何访问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>

How about:怎么样:

$.ajax({
    url: "<path>/Edit",
    type: "POST",
    data: JSON.stringify(department),
    dataType: "json",
    cache: false,
    success: function (data) {
        [...]
    },
    error: function () {
        [...]
    }
})

You can access data list from json file when using Json.Parse();使用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; }

   }

then parse the response using JSON parser.然后使用 JSON 解析器解析响应。 Now you can read property values from ajax success like this现在您可以像这样从 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM