【问题标题】:How do you post an object using ajax in asp.net?如何在 asp.net 中使用 ajax 发布对象?
【发布时间】:2017-08-18 19:40:53
【问题描述】:

这是产品类别:

public class Product
{
    public int Id { get; set; }
    [Required]
    public string Name { get; set; }
    [Required]
    public string Description { get; set; }
    [Required]
    [Range(1, 1000000)]
    public decimal Price { get; set; }
    [Required]
    public string Category { get; set; }
}

这是我的 .cshtml 页面:

<div class="alert alert-success">
    <span id="responseMessage"></span>
</div>
<div class="form-group">
    <label>Name</label>
    @Html.TextBoxFor(x => x.Name)
</div>
<div class="form-group">
    <label>Price</label>
    @Html.TextBoxFor(x => x.Price)
</div>
<div class="form-group">
    <label>Category</label>
    @Html.TextBoxFor(x => x.Category)
</div>
<div class="form-group">
    <label>Description</label>
    @Html.TextBoxFor(x => x.Description)
</div>
<button id="postButton">Ok</button>

这是我的 javascript:

$(document).ready(function () {
    $("#postButton").click(function () {
        var product = 'product=' +
            JSON.stringify({
                Name: $('#Name').val(),
                Description: $('#Description').val(),
                Price: $('#Price').val(),
                Category: $('#Category').val()
            });


        $.ajax({
            url: "/api/products/postproduct",
            type: "POST",
            data: product,
            dataType: 'json',
            success: function (data, status, xhr) {
                $('#responseMessage').html('Insert status: ' + 
                data.d.status);
            },
            error: function (xhr, status, error) {
                alert('Error occurred: ' + status);
            }
        });
    });
});

这是我的控制器:

    public async Task<IHttpActionResult> PostProduct(Product product)
    {
        if (ModelState.IsValid)
        {
            await Repository.SaveProductAsync(product);
            return Ok();
        }
        else
        {
            return BadRequest(ModelState);
        }
    }

提前谢谢你。 ajax 帖子命中控制器(我在那里设置了一个断点),但是当我将鼠标悬停在产品参数上时,没有值进入。如果您需要更多信息,请告诉我。

【问题讨论】:

  • 您是否尝试过放弃'product=' 部分而只发送不带字符串化的对象?
  • 如果您使用的是 .net core,请确保在控制器操作中将 [FromBody] 添加到请求模型中。

标签: c# jquery asp.net ajax


【解决方案1】:

我认为你的问题是:

您正在将数据传递给您的方法,但参数还不是 Product 类型。您可能需要将参数类型更改为更通用的object 类型。然后你可以将它转换为你想要的product 模型。

一旦数据进入您的控制器,它需要一个强类型对象product。因此,将参数类型更改为object 允许您解析object 的每个子项。

【讨论】:

    【解决方案2】:

    将控制器中的参数名称更改为此 public async Task PostProduct(Product Product)

    或者在jquery中改变 数据:{“产品”,产品}

    希望这会奏效。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-04
      • 2012-06-22
      相关资源
      最近更新 更多