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> CREATE MY ACCOUNT</button>
</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.