I am working on a mvc project, and having problem with json.
i have created a demo project with list of colors
public JsonResult GetResult()
{
List<string> strList = new List<string>();
strList.Add("white");
strList.Add("blue");
strList.Add("black");
strList.Add("red");
strList.Add("orange");
strList.Add("green");
return this.Json(strList);
}
i am able to get these on my page, but when i try to delete one color, that is when i send the following using jquery
function deleteItem(item) {
$.ajax({
type: "POST",
url: "/Home/Delete/white",
data: "{}",
contentType: "application/json; charset=utf-8",
success: ajaxCallSucceed,
dataType: "json",
failure: ajaxCallFailed
});
}
the controler action
public JsonResult Delete(string Color) {}
Color always returns null, even if i have specified "/Home/Delete/white" in the url.
i know i am doing something wrong or missing something, but not able to find out what.
please can any one guide me in the right direction.
Check your routes. (Usually set in /global.asax.)
Try changing your url to:
"/Home/Delete?Color=white"
The reason is that there isn't a route set up to handle a string called color, like you have.
Have a look at this for info on how to create a custom route that will handle your current url format.
try this above the default
routes.MapRoute("Color", "{controller}/{action}/{color}", new { controller = "Home", action = "Index", Color = "" });
Just a common public opinion: It's very strange to Pascal-case method parameters as you do...
Renaming your controller action parameter to id
would do the trick just fine (in case your default route is defined as {controller}/{action}/{id}
).
[HttpPost]
public JsonResult Delete(string id)
{
// do what's required
}
And don't forget to put the attribute on your action method, otherwise a web crawler would be able to delete all your colour entries.
Either use HttpPost
or even better HttpDelete
, because you do use Ajax request anyway, so you can issue a DELETE request.