UpdateModule is a function used for update module details. It's not a view page.
When click on update, it returns 500 (internal server error) or 404 error
please help to fix it
$.ajax({
type: 'POST',
url: '#Url.Action("ETM_PRODUCTS","UpdateModule")',
//contentType: 'application/json',
datatype: JSON,
data: { 'ModuleID': ModuleID, 'ModuleName': ModuleName, 'ModuleDescription': ModuleDescription },
success: function (data) {
if (data == true) {
alert("Updated Successfully");
}
},
error: function (msg) {
alert("Error")
},
});
c#
public JsonResult UpdateModule(int ModuleID,string ModuleName,string ModuleDescription) {
bool status = true;
PROD_MODULE tabledata = db.PROD_MODULE.Where(x => x.ETM_MODULE_ID == ModuleID)
.FirstOrDefault();
tabledata.NAME = ModuleName;
tabledata.DESCRIPTION = ModuleDescription;
db.SaveChanges();
return Json ( status, JsonRequestBehavior.AllowGet );
}
There is a problem in the way you call Url.Action.
The first parameter is the action and the second the controller.
Here is the documentation : link
Related
I'm having a hard time getting the data from client but my code on visual studio when I'm on a breakpoint it gets the data but I cant receive it on my browser.
Here's my AJAX call
function GetRecord() {
var elemEmployee = 55;
var startDT = $('#searchFilterStartDate').val();
var endDT = $('#searchFilterEndDate').val();
$.ajax({
url: "/Modules/GetDTRRecord",
type: "GET",
data: {
EmployeeID: elemEmployee,
DateFrom: endDT,
DateTo: startDT,
},
dataType: "json",
success: function(data) {
console.log('Data Success ');
console.log(data);
}
});
}
here's my controller:
[HttpGet]
public List<DTRRecordList.Entity> GetDTRRecord(DTRRecordList.Entity data)
{
var entity = new DTRRecordList();
return entity.GetDTR(data);
}
As you can see below I got 38 records but I can't receive it on my js even that console.log('Data Success') is not shown on my console.
You need to return JSON from your Controller method. You can change your method to:
[HttpGet]
public JsonResult GetDTRRecord(DTRRecordList.Entity data)
{
var entity = new DTRRecordList();
var getDTR= entity.GetDTR(data);
return Json(new {dtrData= getDTR});
}
And in your Ajax call:
$.ajax({
url: "/Modules/GetDTRRecord",
type: "GET",
data: {
EmployeeID: elemEmployee,
DateFrom: endDT,
DateTo: startDT,
},
dataType: "json",
success: function(data) {
console.log('Data Success ');
console.log(data.dtrData);
},
error: function(error) {
console.log(error)
}
});
After a discussion with O.P and seeing the code, it was found that the issue was happening because the form submit was happening which was causing the page to reload twice. After removing the form event and adding the click event in:
$(document).ready(function () {
//On Clink "Search Button"
$("#searchbtn").click(
function () { GetRecord(); });
});
The data seems to be coming as expected.
I have an Ajax Call and a Controller with some methods and there is something weird.
The Ajax call can reach the Controller Method. The method is returning the value perfectly, no errors, nothing. However, in the AJAX the return is coming with error (not on success of Ajax).
Moreover, If I inspect the return I can see the correct values on responseJson, but the status is 404 and statusText is "error" ({"readyState":4,"status":404,"statusText":"error"})
Anyone have an idea what is going on? There is no error in backend, however error in Ajax.
Controller Method
public JsonResult SceneListUpdated(string sceneId)
{
SceneListModel model = new SceneListModel();
var licenseValidationState = KeygenLicenseState.CheckLicense();
if (licenseValidationState == 0)
{
SceneListService sceneService = new SceneListService();
model = sceneService.GetSceneListUpdated(sceneId);
return Json(new { Success = true, data = model }, JsonRequestBehavior.AllowGet );
}
return Json(new { Success = false, data = "" }, JsonRequestBehavior.AllowGet);
}
Ajax Function
$.ajax({
url: "/api/test/SceneList/SceneListUpdated?sceneId=" + sceneIdAux, //Method in controller
type: "GET",
contentType: "application/json; charset=utf-8",
datatype: "json",
success: function (e) {
},
error: function (data) {
}
});
try to fix the ajax
$.ajax({
url: "/api/test/SceneList/SceneListUpdated/"+ sceneIdAux, //Method in controller
type: "GET",
success: function (e) {
},
error: function (data) {
}
});
and maybe you can try one of these routing since you have 404
[Route("{sceneId}")]
[Route("~/api/SceneList/SceneListUpdated/{sceneId}")]
public JsonResult SceneListUpdated(string sceneId)
I am calling jquery function on dropdown value change jquery method is ,
function MyFunction() {
alert($('#DDlSurvey').val());
$.ajax({
url: "#Url.Action("GetSelectedQuestion", "ConductSurveyController")",
data: { prefix: $('#DDlSurvey').val() },
type: "GET",
dataType: "json",
success: function (data) {
// loadData(data);
alert(data)
alert("Success");
},
error: function () {
alert("Failed! Please try again.");
}
});
//$('#YourLabelId').val('ReplaceWithThisValue');
}
</script>
Function I'm calling and I am getting dropdown value alert
Now, Function that I am calling is "GetSelectedQuestion" in controller "ConductSurveyController"
Method is like ,
[HttpPost]
public JsonResult GetSelectedQuestion(int prefix)
{
List<SelectList> Questions=new List<SelectList>();
// Here "MyDatabaseEntities " is dbContext, which is created at time of model creation.
SurveyAppEntities ObjectSur = new SurveyAppEntities();
// Questions = ObjectSur.Surveys.Where(a => a.ID.Equals(prefix)).toToList();
I don't think this method is calling as I am getting error
"Failed! Please try again"
From my script.
Hopes for your suggestions
Thanks
var e = from q in ObjectSur.Questions
join b in ObjectSur.SurveyQuestions on q.ID equals b.QuestionID where b.SurveyID.Equals(prefix)
select q ;
return new JsonResult { Data = e, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}
I think you are using controller name straight forward. your ajax code be something like this.
var PostData= { prefix: $('#DDlSurvey').val() }
var ajaxOptions = {
type: "GET",
url: '#Url.Action("GetSelectedQuestion", "ConductSurvey")',//Actionname, ControllerName
data: PostData,
dataType: "json",
success: function (result) {
console.log(result);
},
error: function (result) {
}
};
$.ajax(ajaxOptions);
Your method in your controller is decorated with HttpPost, while in your ajax you have specified the type of your request is get . You can either change your method to get like this:
[HttpGet]
public JsonResult GetSelectedQuestion(int prefix)
{
}
Or change your request type to post in your Ajax call:
$.ajax({
url: "#Url.Action("GetSelectedQuestion", "ConductSurveyController")",
data: { prefix: $('#DDlSurvey').val() },
type: "Post",
Also the Controller is redundant in ConductSurveyController, you need to remove it and simply call it as ConductSurvey:
url: '#Url.Action("GetSelectedQuestion", "ConductSurvey")',
I want to display in a webpage an exception message raised in my .NET code in the error part of an ajax request:
[HttpPost]
[AllowAnonymous]
public virtual ActionResult AuthenticateUser(string somedata)
{
throw new Exception("Ooops!!");
}
JS code:
jQuery(document).ready(function () {
jQuery.ajax(
'#Url.Action("AuthenticateUser")',
{
contentType: "application/json; charset=utf-8",
dataType: "json",
data: {
somedata:somedata
},
success: function (result) {
if (result == 'true') {
window.location = '#Url.Content(Request["returnUrl"])';
}
},
error: function (response) {
var responseJson = jQuery.parseJSON(response.responseText);
$('#errorMessage').text(responseJson.Message);
$('#progress_message').text("");
},
type: 'post'
}
);
});
The error I get in "response" is HTML code and I want to parse it to get the exception message I throw from the server side. So, the better approach I came up with was to return a Json response, but despite specifying "json" as datatype I still receive HTML code in "response", so... what am I doing wrong? Is the problem the "Exception" object I throw from the server side?
The problem is that whenever an exception is thrown in a controller, it will always trigger asp.net's error page and return whatever is configured for the 500 http status code (the default result is the "yellow page of death" which is an html), what you are trying to do is custom error handling and there are several ways of doing it in depth explanation is present in this blog
One way you could do this is by overriding the OnException method:
protected override void OnException(ExceptionContext filterContext)
{
filterContext.Result = Json(new {Message = filterContext.Exception.Message});
filterContext.ExceptionHandled = true;
}
This will replace the default result for an internal server error (500) with a json result containing the error message, which can be obtained like below
jQuery.ajax(
'#Url.Action("AuthenticateUser")',
{
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
console.log(result);
},
error: function (response) {
var responseJson = jQuery.parseJSON(response.responseText);
console.log(responseJson.Message); //Logs the exception message
},
type: 'post'
});
This will catch errors Controller wise, if you want to do this application wise you will have to go a little deeper on the blog's methods (probably with the "HandleError" Attribute)
In the end I returned JsonResults and handled the message from the view:
Server code:
[HttpPost]
[AllowAnonymous]
public virtual JsonResult AuthenticateUser(string somedata)
{
if (ok)
return new JsonResult() {Data="ok"}
return new JsonResult() {Data= "Missing data blah"}
}
And in javascript:
success: function (result) {
if (result == 'ok') {
window.location = '#Url.Content(Request["returnUrl"])';
return;
}
$('#progress_message').text("");
$('#errorMessage').text(result);
},
I have a very simple ajax call to refresh some data on my webpage, but it doesn't seem to fire correctly. The data that the call brings back is the same everytime even if the underlying data changes.
The ajax call looks like this:
function RefreshContent() {
//create the link
var link = "/Address/ListByAjax/" + $('#Id').val();
$.ajax({
type: "GET",
url: link,
success: function (data) {
$("#Address").html(data);
},
error: function (req, status, error) {
alert('an error occured: ' + error);
}
});
}
My controller looks like this:
public ActionResult ListByAjax(int Id)
{
var list = db.Address.Where(i => i.Person_Id == Id);
return PartialView("_List", list.ToList());
}
Try setting the cache to false in your ajax call - that will force the browser to send the request through to the controller:
function RefreshContent() {
//create the link
var link = "/Address/ListByAjax/" + $('#Id').val();
$.ajax({
type: "GET",
url: link,
cache: false,
success: function (data) {
$("#Address").html(data);
},
error: function (req, status, error) {
alert('an error occured: ' + error);
}
});
}
Use
ajaxSetup({ cache: false }); });
This turns off caching for all ajax calls made by your app.