简体   繁体   中英

How to send model data from view to api controller using ajax

I am trying to send the value from my this view to given API controller.It is working when i hard-code the json data.I am unable to send the data of id and brandname when i press the button since it is in table. How do I make it work?Please help

  <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>
    }

I have a brand API. And it post API controller is

    [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);

    }

There are many ways to go about this. One would be to select the cells and extract the data to send it later on:

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

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

  ...

You are using DisplayFor, which is used to display the lable, or name of the text field. you need to replace DisplayFor with EditorFor where you are populating data in foreach loop. Also you should use razor HTML helper form or AJAX helper form

There are different approaches to get controls values from views, one solution can be wrap the <table>...</table> with a form tag like

<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>

Access control values like

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');
     }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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