【问题标题】:How to send model data from view to api controller using ajax如何使用 ajax 将模型数据从视图发送到 api 控制器
【发布时间】:2018-05-20 05:02:06
【问题描述】:

我正在尝试将值从我的这个视图发送到给定的 API 控制器。当我对 json 数据进行硬编码时,它正在工作。当我按下按钮时,我无法发送 id 和品牌名称的数据,因为它是在表中。我如何使它工作?请帮助

  <table class="table">
    <tr>
        <th>
            @Html.DisplayNameFor(model => model.Brand.BrandName)
        </th>
                <th>
            @Html.DisplayNameFor(model => model.ProductName)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.Price)
        </th>

        <th></th>
    </tr>

@foreach (var item in Model) {
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.Brand.BrandName)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.ProductName)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Price)
        </td>
      <td><input type="button" id="Save" /></td>

    </tr>
}

</table>
@section scripts {
<script> 
    $(document).ready(function () {
        $("#Save").click(function () {

            var brand = { 'id':1, 'brandname': 'abc' }

            $.ajax({
                url: 'http://localhost:51429/api/brands',
                type: 'POST',
                dataType: 'json',
                data: brand,
                success: function (data, textStatus, xhr) {
                    console.log(data);
                },
                error: function (xhr, textStatus, errorThrown) {
                    console.log('Error in Operation');
                }
            });


        });
    });

   </script>
    }

我有一个品牌 API。它发布 API 控制器是

    [HttpPost]
    public IHttpActionResult Post([FromBody]Brands brand)
    {
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }
        db.Brands.Add(brand);
        db.SaveChanges();

        return CreatedAtRoute("DefaultApi", new { id = brand.Id }, brand);

    }

【问题讨论】:

  • 尝试在您的 JSON 请求中添加 Content-type 标头:application/json。此外,在发送之前序列化您的数据:JSON.strinigify(brand) 而不仅仅是brand。编辑:在 jQuery 中设置内容类型是在设置调用中添加一个新字段:contentType: "application/json; charset=utf-8"
  • 我如何从模型中添加 id 和品牌名称并从这个视图发送到 ajax。
  • 由于数据在表中,所以我无法访问它的 id 或者我不知道该怎么做。
  • Brands 是什么以及生成的 HTML 代码是什么样的?
  • Brands 是具有 Id 和 Brandname 的模型。在此视图中点击保存按钮后,它仅将 id 和品牌名称传递给 post api。

标签: c# jquery ajax api


【解决方案1】:

有很多方法可以解决这个问题。一种是选择单元格并提取数据以便稍后发送:

$("#Save").click(function () {
  var $button = $(this);
  var $cells = $button.closest("tr").find("td");

  var brand = {..., 'brandname': $cells.eq(0).html(), ...}

  ...

【讨论】:

  • 谢谢我会试试这个
  • 无法从 var brand = { 'id': $cells.eq(1).val(), 'brandname': $cells.eq(2).val() }
  • @Sres “无法从中获取价值”究竟是什么意思?
【解决方案2】:

您正在使用 DisplayFor,它用于显示标签或文本字段的名称。您需要将 DisplayFor 替换为 EditorFor 在 foreach 循环中填充数据的位置。 你也应该使用 razor HTML helper form 或 AJAX helper form

【讨论】:

  • 如果 api 控制器在不同的项目中,是否可以使用 html helper 表单?\
【解决方案3】:

有不同的方法可以从视图中获取控件值,一种解决方案可以是 wrap &lt;table&gt;...&lt;/table&gt;form 标签,如

<form id="Form1">
<table class="table">
 <tr>
    <th>
        @Html.DisplayNameFor(model => model.Brand.BrandName)
    </th>
            <th>
        @Html.DisplayNameFor(model => model.ProductName)
    </th>
    <th>
        @Html.DisplayNameFor(model => model.Price)
    </th>

    <th></th>
</tr>

@foreach (var item in Model) {
<tr>
    <td>
        @Html.DisplayFor(modelItem => item.Brand.BrandName)
    </td>
    <td>
        @Html.DisplayFor(modelItem => item.ProductName)
    </td>
    <td>
        @Html.DisplayFor(modelItem => item.Price)
    </td>
  <td><input type="button" id="Save" /></td>

 </tr>
}

</table>
</form>

访问控制值,如

var brand = $('#Form1').serialize();

$.ajax({
     url: 'http://localhost:51429/api/brands',
     type: 'POST',
     dataType: 'json',
     data: brand,
     success: function (data, textStatus, xhr) {
          console.log(data);
     },
     error: function (xhr, textStatus, errorThrown) {
            console.log('Error in Operation');
     }
});

【讨论】:

  • 但我只需要 id 和 brandname 所以我认为序列化和发送所有数据是不对的。
猜你喜欢
  • 2011-08-09
  • 2021-03-25
  • 2016-03-21
  • 2014-12-06
  • 2021-04-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多