我想要做的就是向控制器发布一个邮政编码,对邮政编码进行一些操作,并将更改发回给邮政编码。 但我的参数a始终为空。 谁能告诉我我做错了什么?
这是我的代码:
视图:
<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'); } }); });控制器:
public ViewResult Index() { return View(); } [HttpPost] public ActionResult Index(string a) { return Json("test", JsonRequestBehavior.AllowGet); }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); }最满意答案
首先,你在页面中包含jQuery的两个版本,我强烈建议你删除一个。 如果您不支持旧版浏览器,请使用1.9如果您想支持IE9或更低版本,请使用2.0 。
另外,当jQuery将提供的data序列化时,它不一定是以JSON格式发送的,因此contentType: "application/json; charset=utf-8"设置可能会令MVC模型绑定器混淆,将其删除。
最后,请注意, zipcode仅在页面加载时设置,您还应在发送AJAX请求之前检索它。
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.
更多推荐
发布评论