簡體   English   中英

ASP.Net Core 錯誤:JSON 值無法轉換為 System.String

[英]ASP.Net Core Error : The JSON value could not be converted to System.String

我正在嘗試在 Asp.net 核心中執行搜索功能,這是我的控制器

[HttpPost("searchbyname")]
   public async Task<ActionResult<List<SelectedChildDto>>> SearchByName([FromBody]string firstName)
   { if (string.IsNullOrWhiteSpace(firstName)) { return new List<SelectedChildDto>(); }
            return await _context.Children
                .Where(x => x.FirstName.Contains(firstName))
                .OrderBy(x => x.FirstName)
                .Select(x => new SelectedChildDto { Cld = x.Cld, ChildCode = x.ChildCode, 
                 FirstName = x.FirstName, PhotoPath = x.PhotoPath })
                .Take(5)
               .ToListAsync();               
              
        }

我有模型中的這個 DTO 類

namespace API.Dtos
{
    public class SelectedChildDto
    {
      
        public int Cld { get; set; }

        public string ChildCode { get; set; }
     
        public string FirstName { get; set; }
         public string PhotoPath { get; set; }
    }
}

“錯誤”:{“$”:[“JSON 值無法轉換為 System.String。路徑:$ | LineNumber:0 | BytePositionInLine:1。” ] }

我不知道您如何在視圖中傳遞firstName ,但您的數據格式不正確。

如果你只是傳遞了一個字符串firstName而沒有[FromBody] ,你可以參考下面的代碼。

控制器:

 [HttpGet]
 public async Task<IActionResult> SearchByName()
 {
     var children = from m in _context.Children
                       select m;
     return View(await children.ToListAsync());
 }
[HttpPost]
public async Task<ActionResult<List<SelectedChildDto>>> SearchByName(string firstName)
{
    if(string.IsNullOrWhiteSpace(firstName))
    {
        return new List<SelectedChildDto>();
    }
    return await _context.Children
        .Where(x => x.FirstName.Contains(firstName))
        .OrderBy(x => x.FirstName)
        .Select(x => new SelectedChildDto
        {
            Id = x.Id,
            ChildCode = x.ChildCode,
            FirstName = x.FirstName,
            PhotoPath = x.PhotoPath
        })
        .Take(5)
       .ToListAsync();
}

看法:

@model IEnumerable<API.Models.SelectedChildDto>
<form asp-controller="Home" asp-action="SearchByName" method="post">
    <p>
        Title:<input type="text" name="firstName"/>
        <input type="submit" value="check"/>
    </p>
</form>
<table class="table">
    <thead>
        <tr>
            <th>
                @Html.DisplayNameFor(model => model.ChildCode)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.FirstName)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.PhotoPath)
            </th>
        </tr>
    </thead>
    <tbody>
@foreach (var item in Model) {
        <tr>
            <td>
                @Html.DisplayFor(modelItem => item.ChildCode)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.FirstName)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.PhotoPath)
            </td>
        </tr>
}
    </tbody>
</table>

測試結果: 在此處輸入圖像描述 在此處輸入圖像描述 在此處輸入圖像描述

如果你想使用[FromBody] ,你可以參考下面的代碼。 控制器:

 [HttpGet]
 public async Task<IActionResult> SearchByName()
 {
     var children = from m in _context.Children
                       select m;
     return View(await children.ToListAsync());
 }
[HttpPost]
public async Task<ActionResult<List<SelectedChildDto>>> SearchByName([FromBody] string firstName)
{
    if(string.IsNullOrWhiteSpace(firstName))
    {
        return new List<SelectedChildDto>();
    }
    return await _context.Children
        .Where(x => x.FirstName.Contains(firstName))
        .OrderBy(x => x.FirstName)
        .Select(x => new SelectedChildDto
        {
            Id = x.Id,
            ChildCode = x.ChildCode,
            FirstName = x.FirstName,
            PhotoPath = x.PhotoPath
        })
        .Take(5)
       .ToListAsync();
}

看法:

@model IEnumerable<API.Models.SelectedChildDto>
<p>
        Title:<input type="text" id="firstName" name="firstName"/>
        <button class="btn btn-primary" onclick="Inquire()">check</button>
</p>

<table class="table">
    <thead>
        <tr>
            <th>
                @Html.DisplayNameFor(model => model.ChildCode)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.FirstName)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.PhotoPath)
            </th>
            
        </tr>
    </thead>
    <tbody>
@foreach (var item in Model) {
        <tr>
            <td>
                @Html.DisplayFor(modelItem => item.ChildCode)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.FirstName)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.PhotoPath)
            </td>
            
        </tr>
}
    </tbody>
</table>

<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script type="text/javascript">
    function Inquire() 
    {
        $.ajax({
            contentType: 'application/json; charset=utf-8',
            dataType: 'JSON',
            url: '/Home/SearchByName',
            type: "post",
            data: JSON.stringify($("#firstName").val()),
            success: function (result) {
                alert(JSON.stringify(result));
            },
            failure: function (response) {
                console.log(response);
            }
        });
    }
</script>

測試結果: 在此處輸入圖像描述 在此處輸入圖像描述

該問題與控制器的單個[FromBody] string firstName參數的正文文本的 System.Text.Json 反序列化有關。 例如,您只需要在正文中發送"John" ,而不是功能齊全的 JSON {"firstName": "John"}

還要檢查類似問題的答案

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM