Reputation: 3239
All I want to do is post a zipcode to a controller, do some stuff to the zipcode, and post back the changes to the zipcode. But my parameter a is always null. Can anyone tell me what I am doing wrong?
Here is my code:
View:
<input type="text" id="zipcode" />
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
var serviceURL = '/Employer/employer/index';
var zipcode = $("#zipcode").val();
$("#zipcode").blur(function () {
$.ajax({
type: "POST",
url: serviceURL,
data: {'a':zipcode},
contentType: "application/json; charset=utf-8",
success: successFunc,
error: errorFunc
});
function successFunc(data, status) {
alert(data);
}
function errorFunc() {
alert('error');
}
});
});
Controller:
public ViewResult Index()
{
return View();
}
[HttpPost]
public ActionResult Index(string a)
{
return Json("test", JsonRequestBehavior.AllowGet);
}
Upvotes: 1
Views: 45
Reputation: 337700
Firstly you are including two versions of jQuery in your page, I strongly suggest you remove one. Use 1.9
if you want to support IE9 and lower, 2.0
+ if you don't support legacy browsers.
Also, when jQuery serialises the data
provided it is not necessarily sent in JSON format, so the contentType: "application/json; charset=utf-8"
setting may be confusing the MVC model binder, remove it.
Finally, note that zipcode
is only set on page load, you should also retrieve it before the AJAX request is sent.
Upvotes: 1
Reputation: 56716
Notice that you are storing zipcode value into the variable right in the document.ready handler, before user had a chance to interact with it. You should do this in the blur handler, to make sure you take the actual value:
$("#zipcode").blur(function () {
var zipcode = $("#zipcode").val();
$.ajax({
Upvotes: 4