Hasanuzzaman
Hasanuzzaman

Reputation: 1862

Why I got my model attributes null during a put request in web api?

I send a PUT request from my View to web API controller using JQuery and Ajax. It hit my web api controller but my model attributes are null.

Here Is my Controller Code:

public HttpResponseMessage Put(Int64 id, 
           [FromUri] CompanyInformation companyInformation) {
  try {
    if (ModelState.IsValid) {
      if (IsUniq(companyInformation.Name)) {
        _smUnitOfWork.CompanyInformations.Update(companyInformation);
        _smUnitOfWork.Save();
        return Request.CreateResponse(HttpStatusCode.OK, 
           string.Format(Messagess.UpdatedSuccess, 
                         companyInformation.Name));
      }
    }
    return Request.CreateResponse(HttpStatusCode.BadRequest, 
           string.Format(Messagess.AlreadyExist, 
                         companyInformation.Name, TypeNameMessages));
  } catch (Exception) {
    return Request.CreateResponse(HttpStatusCode.BadRequest, 
                                  Messagess.UnbaleToProcess);
  }
}

My View is :

  <div id="companySetup">
   @using (Html.BeginForm(null,null, FormMethod.Post, new{id="MyId"}))
   {
    <div>
        <div>
            <h2>Company Setup</h2>
            <ul>
                <li>
                    @Html.LabelFor(x => x.Name)
                    @Html.TextBoxFor(x => x.Name)
                </li>
                <li>
                    @Html.LabelFor(x => x.FirstAddress)
                    @Html.TextAreaFor(x => x.FirstAddress)
                </li>
                <li>@Html.LabelFor(x => x.SecondAddess)
                    @Html.TextAreaFor(x => x.SecondAddess)
                </li>
                <li>
                    @Html.LabelFor(x => x.ContractDeatils)
                    @Html.TextAreaFor(x => x.ContractDeatils)
                </li>
                <li>
                    @Html.LabelFor(x => x.Email)
                    @Html.TextBoxFor(x => x.Email, new { type = "email" })
                </li>
                <li>
                    @Html.LabelFor(x => x.Web)
                    @Html.TextBoxFor(x => x.Web)
                </li>
            </ul>
            @Html.HiddenFor(x => x.Id)
        </div>
        <div class="buttonAlinment">
            <input type="submit" value="Reset" />
            <input type="submit" value="Update" />
        </div>
    </div>
}

My JavaScript is :

var updateCompanyInfo = function () {
var companyInformation = {
    "Name": $("#Name").val(),
    "FirstAddress": $("#FirstAddress").val(),
    "SecondAddess": $("#SecondAddess").val(),
    "ContractDeatils": $("#ContractDeatils").val(),
    "Web": $("#Web").val(),
    "Id": $("#Id").val(),
    "Email": $("#Email").val(),
};

$.ajax({
    url: '/api/CompanyInformation/' + $('#Id').val(),
    type: 'PUT',
    contentType: "application/json; charset=utf-8",
    data: { companyInformation: companyInformation },
    success: function (result) {
        alert("Done");
    }
});

};

In debug mode it shows : enter image description here

I don`t understand where i am wrong.

Upvotes: 1

Views: 718

Answers (1)

Maggie Ying
Maggie Ying

Reputation: 10185

There are 2 issues here

  1. Your companyInformation is expecting to come from the Uri but then you are sending the data in the body of the request.
  2. Currently the body is in the form urlencoded content but the data type you specified is in application/json

There are several ways to fix this, and this is what I would do. First, remove [FromUrl] from the companyInformation parameter of you PUT method:

 public HttpResponseMessage Put(Int64 id, CompanyInformation companyInformation) 
 {
     ...
 }

Then use JSON.stringify(...) to convert the data into JSON on the client side:

$.ajax({
    url: '/api/CompanyInformation/' + $('#Id').val(),
    type: 'PUT',
     contentType: "application/json; charset=utf-8",
     data: JSON.stringify(companyInformation),
     success: function (result) {
         alert("Done");
     }
 });

Upvotes: 2

Related Questions