ASP.Net核心错误:JSON值无法转换为System.String

c9x0cxw0  于 2022-12-15  发布在  .NET
关注(0)|答案(2)|浏览(267)

我尝试在www.example.com内核中执行搜索功能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。路径:$|行号:0|行内字节位置:1.”] }

wvt8vs2t

wvt8vs2t1#

我不知道您如何在视图中传递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>

测试结果:第一节第三节第一节第一节第四节第一节

deyfvvtc

deyfvvtc2#

此问题是由System.Text.Json对控制器的单个[FromBody] string参数进行反序列化引起的。请检查此答案以了解如何修复此问题。

相关问题