Ajax POST has null entry for parameter [assetID]?
I am using GridMVC to render a button in one of my grid columns to act as a verification button on assets. Basically when the button is clicked, I want to find the relevant asset in the DB based on ID and set the [verified_date]
to the DateTime.Now
.
columns.Add().Encoded(false).Sanitized(false).RenderValueAs(o => @<a href="#" class="btn btn-default btn-sm noDecoration" onclick="verifyAsset(@o.Id)"><span class="glyphicon glyphicon-ok"></span> @*View*@</a>).SetWidth(15);
Using a hyperlink tag in the above, I am calling my verifyAsset()
javascript function:
@section Scripts {
<script type="text/javascript">
function verifyAsset(assetID) {
alert("The assetID is: " + assetID);
var data = { verified_date: assetID };
alert("Got this far...");
$.ajax({
type: "POST",
dataType: "JSON",
url: '@Url.Action("verifyAsset", "INV_Assets")',
data: data,
success: function (resp) {
alert("Success! Asset " + resp.ID + " successfully verified on " + resp.VDate);
},
error: function (resp) {
alert("There was an error verifying this Asset...");
}
});
}
</script>
}
When I try to run through the funcitonality though, my ajax
is always error
ing and the breakpoint on my Controller Action verifyAsset()
is never being reached:
[HttpPost]
public JsonResult verifyAsset(int assetID)
{
INV_Assets asset = db.INV_Assets.Find(assetID);
asset.verified_date = DateTime.Now;
try
{
if (ModelState.IsValid)
{
db.SaveChanges();
}
}
catch (Exception ex)
{
Elmah.ErrorSignal.FromCurrentContext().Raise(ex);
}
return Json(new { ID = asset.Id, VDate = asset.verified_date }, JsonRequestBehavior.AllowGet);
}
The error returned in my Elmah
log is: The parameters dictionary contains a null entry for parameter 'assetID' of non-nullable type 'System.Int32' for method 'System.Web.Mvc.JsonResult verifyAsset(Int32)' in 'InventoryTracker.Controllers.INV_AssetsController'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter. Parameter name: parameters
The parameters dictionary contains a null entry for parameter 'assetID' of non-nullable type 'System.Int32' for method 'System.Web.Mvc.JsonResult verifyAsset(Int32)' in 'InventoryTracker.Controllers.INV_AssetsController'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter. Parameter name: parameters
The parameters dictionary contains a null entry for parameter 'assetID' of non-nullable type 'System.Int32' for method 'System.Web.Mvc.JsonResult verifyAsset(Int32)' in 'InventoryTracker.Controllers.INV_AssetsController'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter. Parameter name: parameters
.
Can anyone spot where I might be going wrong? In the first alert()
of my script I've confirmed the correctly ID
value is being passed to the function in variable assetID
, however I do notice that if I try to set the data
as: var data = { verified_date: @Convert.ToInt32(assetID) };
the assetID
flags as not exist in the current context
...?
EDIT :
The following is similar code I have gotten to work before:
Script :
$('#submitNewModel').click(function () {
var form = $(this).closest('form');
var data = { description: document.getElementById('textNewModel').value };
//var data = { model_description: document.getElementById('textNewModel').value, created_date: @DateTime.Now, created_by: @System.Environment.UserName };
$.ajax({
type: "POST",
dataType: "JSON",
url: '@Url.Action("createNewModel", "INV_Assets")',
data: data,
success: function (resp) {
$('#selectModel').append($('<option></option>').val(resp.ID).text(resp.Text));
form[0].reset();
$('#createModelFormContainer').hide();
},
error: function () {
alert("ERROR!");
}
});
});
INV_AssetsController - createNewModel() :
[HttpPost]
public JsonResult createNewModel(string description)
{
INV_Models model = new INV_Models()
{
// ID auto-set during save.
model_description = description,
created_date = DateTime.Now,
created_by = System.Environment.UserName
};
try
{
if (ModelState.IsValid)
{
db.INV_Models.Add(model);
db.SaveChanges();
}
}
catch (Exception ex)
{
Elmah.ErrorSignal.FromCurrentContext().Raise(ex);
}
return Json(new { ID = model.Id, Text = model.model_description }, JsonRequestBehavior.AllowGet);
}
After reviewing gutsmania
's answer, I realized he was indeed correct and I had mentally jumped the gun declaring my data
field to be passing as verified_date
when all I was intending was to pass the ID
value to the expected parameter in my controller action. Since verification_date
does not equal assetID
(the expected parameter), the action was never actually called and failed out as NULL
.
Updated code below:
SCRIPT :
<script type="text/javascript">
function verifyAsset(assetID) {
alert("The assetID is: " + assetID);
var data = { asset_ID: assetID };
alert("Got this far...");
$.ajax({
type: "POST",
dataType: "JSON",
url: '@Url.Action("verifyAsset", "INV_Assets")',
data: data,
success: function (resp) {
alert("Success! Asset " + resp.ID + " successfully verified on " + resp.VDate);
},
error: function (resp) {
alert("There was an error verifying this Asset...");
}
});
}
</script>
INV_AssetsController - verifyAssets() :
[HttpPost]
public JsonResult verifyAsset(int asset_ID)
{
INV_Assets asset = db.INV_Assets.Find(asset_ID);
asset.verified_date = DateTime.Now;
try
{
if (ModelState.IsValid)
{
db.SaveChanges();
}
}
catch (Exception ex)
{
Elmah.ErrorSignal.FromCurrentContext().Raise(ex);
}
return Json(new { ID = asset.Id, VDate = asset.verified_date }, JsonRequestBehavior.AllowGet);
}
first of all, this probably isn't going to work.
var data = { verified_date: @Convert.ToInt32(assetID) };
Unless you have assetID scoped as a serverside variable (and the error message seems to indicate you don't). You can't use Razor helpers on JS objects. That's all that error message is indicating.
Secondly, you're hitting your controller, which is good, but it's not picking up your parameter, which is bad.
I would look at this line:
var data = { verified_date: assetID };
Your controller is looking for a variable named assetID and you're passing it something called verified_date. I don't have VS available at the moment to doublecheck but I know I've run into these sorts of issues when there's a disjoint between the expected parameter name and that which is being passed in via the ajax request. Use Fiddler or some other such tool to inspect what you're actually sending, but since you're not explictly setting your contentType in the ajax call, your message body is likely something like verified_date=someValue and your controller doesn't see the actual param it's looking for so it just takes in NULL.
Generally how I handle request to the server is to test it using a tool like postman. This will allow you to get the Post call working without code. I would just use the key value pair of form data and then tag your call with like so:
[HttpPost]
[Route("{assetID}")]
public JsonResult verifyAsset(int assetID)
{
That should get it for you. Then you need to take what you have learned from postman and do the same in javascript.
Edit: Removed "First of all I wouldn't use JSON to post your Id to the server" from comment.
链接地址: http://www.djcxy.com/p/46160.html上一篇: 错误415:x