0

I have a WEP API controller class which is called by a .cshtml web page in ASP.NET MVC. I am using JSON to transfer the values from the page to the controller. But, although the method is called, the values from the request are not received by the method. Below is my code.

HTML

<form id="register_form" name="register_form" method="post" onsubmit="AjaxRegister();">
    @Html.AntiForgeryToken()
    <div class="twelve columns">
        <label id="message"></label>
    </div>
    <div class="twelve columns">
        <input type="email" id="reg-email" name="signup_email" class="inputbox" required placeholder="Your email">
    </div>
    <div class="twelve columns">
        <input type="date" id="dob" name="dob" class="inputbox" required placeholder="Your date of birth">
    </div>
    <div class="twelve columns">
        <select id="country-list" name="reg-country">
            <option value="AU">Australia</option>
            <option value="NZ">New Zealand</option>
            <option value="US">United States</option>
        </select>
    </div>
    <div class="six columns">
        <input type="password" id="reg-password" name="signup_password" class="inputbox" required placeholder="Desired password">
    </div>
    <div class="six columns">
        <input type="password" id="confirm_password" name="signup_password_confirm" class="inputbox" required placeholder="Confirm password">
    </div>
    <div class="twelve columns">
        <button type="submit" id="signup" name="submit" class="radius alert button"><i class="icon-heart"></i> &nbsp;CREATE MY ACCOUNT</button>&nbsp;
    </div>
</form>

JS

function AjaxRegister() {
    var input = {
        "user": {
            "UserId": 0,
            "Email": jQuery('#reg-email').val(),
            "DateOfBirthTemp": jQuery('#dob').val(),
            "Password": jQuery('#reg-password').val(),
            "CountryCode": jQuery('#country-list').val(),
        }
    };
    jQuery.ajax({
        type: 'POST',
        dataType: 'json',
        url: 'api/v1/user',
        contentType: 'application/json; charset=utf-8',
        data: JSON.stringify(input),
        success: function(data) {
            jQuery('#message').text('Success');
        },
        error: function() {
            jQuery('#message').text('Error');
        },
        async: false
    });
}

WEB API

Controller

public class UserController : BaseApiController
{
    // POST api/<controller>
    public void Post(User value)
    {
        try
        {
            var newUser = unitofwork.UserRepository.Add(value);
            unitofwork.Commit();
        }
        catch (Exception ex)
        {

        }
    }
}

WebApiConfig

public static void Register(HttpConfiguration config) {
    config.MapHttpAttributeRoutes();

    config.Routes.MapHttpRoute(
        name: "DefaultApi",
        routeTemplate: "api/v1/{controller}/{id}",
        defaults: new {
            id = RouteParameter.Optional
        }
    );
}

The post method is called but the value parameter is null. Javascript function is called onsubmit event of the form. I have tried button click as well but same result. Any help would be appreciated.

2 Answers 2

4

Define your input variable in the following manner

var input = {
    "Email" : jQuery('#reg-email').val(),
    "DateOfBirthTemp" : jQuery('#dob').val(),
    "Password" : jQuery('#reg-password').val(),
    "CountryCode" : jQuery('#country-list').val()
};

I am not sure with the DateOfBirthTemp field. The name defined in your json should match exactly with the property name of your defined class.

This is in with the assumption that your User class looks more or less like this

public class User
{
    public string Email { get; set; }
    public DateTime DateOfBirthTemp { get; set; }
    public string Password { get; set; }
    public SomeDatType CountryCode { get; set; }    
}

and you have correctly used data: JSON.stringify(input) to send json data to your web api action.

You ll need to debug and find out where the next problem if any exists...

Possible places

  1. Console.log(input) and check if the values are being sent properly
  2. Check if the control reaches your action
  3. Check if all values have been posted properly
  4. Check if the control returns to the success/error callback of your ajax call.
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! your answer worked. The issue was in the input variable. It was defined wrong with the intermediate user object. When it was removed, the values were received at the web api method.
2

Try to create a object of data you wish to pass to your server side, No need to Use JSON.stringify

function AjaxRegister() {

var input = {};

input.user.UserId = 0;
input.user.Email = jQuery('#reg-email').val();
input.user.DateOfBirthTemp = jQuery('#dob').val();
input.user.Password = jQuery('#reg-password').val();
input.user.CountryCode = jQuery('#country-list').val();


    jQuery.ajax({
        type: 'POST',
        dataType: 'json',
        url: 'api/v1/user',
        data: input,
        success: function (data) {
            jQuery('#message').text('Success');
        },
        error: function () {
            jQuery('#message').text('Error');
        },
        async: false
    });
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.