my Controller actions not hit after deploy mvc3 application on IIS7.5 - asp.net-mvc-3

I develop accounting application in mvc3.it is run correctly in visual studio 2010.After develop some portion i want to check it by deplploy on IIS7.5. it deploy correctly but it does not hit my controller actions which i use to get data from database through AJAX and jquery. below is my controller method.
[HttpPost]
public JsonResult AutocompleteSuggestions(string term)
{
var namelist = objSvc.GetAutoCompData(term);
return Json(namelist, JsonRequestBehavior.AllowGet);
}
below is my javascript function which use this controller function and get the results from database
$(document).ready(function () {
$(function () {
$("#AcCode").autocomplete({
source: function (request, response) {
$.ajax({
url: '#Url.Action("AutocompleteSuggestions", "Home")', //"/Home/AutocompleteSuggestions",
type: "POST", dataType: "json",
data: { term: request.term },
success: function (data) {
response($.map(data, function (item) {
return {
label: item.code, value: item.desc
}
}))
}
})
},
minLength: 1,
select: function (event, ui) {
event.preventDefault();
if (ui.item) {
$("#Descrip").val(ui.item.value);
$("#AcCode").val(ui.item.label);
}
}
});
});
});
it works correctly when run in visual studio 2010 and give me exact results.but after deploy it in iis7.5
it will give error NetworkError: 404 Not Found
"zulfiqar/CBS/JV/#Url.Action(%22GetVNO%22,%20%22JV%22)"
here Zulfiqar is my system name and cbs is application name.
I also add deployable assemblies at publish time.please any one tell me why this give error on IIS.
NOTE:it give the following error in firebug html panel.
Description: HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable. Please review the following URL and make sure that it is spelled correctly.
Requested URL: /CBS/JV/#Url.Action("GetVNO", "JV")

I resolved my problem by adding error message in controller like this.
[HttpPost]
public JsonResult AutocompleteSuggestions(string term)
{
try
{
var namelist = objSvc.GetAutoCompData(term);
return Json(namelist, JsonRequestBehavior.AllowGet);
}
catch (Exception ex)
{
return Json(new { ok = false, message = ex.Message });
}
}
it will return me the exact error in the firebug.Actually it give error in url parameter of autocomplete function." url: '#Url.Action("AutocompleteSuggestions", "Home")', " some illegal characters was passed so the controller was not hit. So i change it and now my application work correctly in IIS.

Related

How to handle AJAX exception in ASP.NET Core MVC and show custom error page?

I have just begun to work with ASP.NET Core MVC and web development in general, and I am struggling to understand how to show an error page from an AJAX call.
What I would like to do is to show a custom page with the error message on if the Ajax call fails. So far I have the following code which takes me to my 500 page when I throw an exception in the controller but how do I get it to show the exceptions message on that page?
StartUp.cs middleware:
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseStatusCodePagesWithReExecute("/Error/Error", "?Code={0}");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
Error controller:
public IActionResult Error(int? Code = null)
{
if (Code.HasValue)
{
if (Code.Value == 404 || Code.Value == 500)
{
var viewName = Code.ToString();
return View(viewName);
}
}
return View();
}
AJAX call:
// Use ajax call to post to the controller with the data
$.ajax({
type: "POST",
url: "/Renewals/GenerateQuotes",
data: { selectedContractIds: ids },
success: function (response) {
// Show success and refresh the page
Toast.fire({
icon: 'success',
title: 'Quotes Generated'
}).then(function () {
location.reload();
});
},
error: function (xhr, status, error) {
// Response message
var response = xhr.responseText;
window.location.href = '#Url.Action("Error", "Error")?Code=' + xhr.status;
}
})

Using AJAX with MVC 5 and Umbraco

I need to use ajax in a partial view to call a function in a mvc controller to return a calculation.
FYI, I am using MVC 5 and Umbraco 7.
I currently have the ajax code within the partial view (will want to move this to a js file at some point).
Here is the ajax code:
function GetTime(name) {
var result = "";
$.ajax({
url: '/TimeDifference/GetTimeDifference',
//url: '#Url.Action("GetTimeDifference", "TimeDifference")',
type: 'GET',
//data: JSON.stringify({ location: name }),
data: ({ location: name }),
contentType: 'application/json; charset=utf-8',
dataType: 'json',
async: false,
cache: false,
success: function (msg) {
result = msg;
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
}
});
return result;
}
Here is the Controller:
public class TimeDifferenceController : Controller
{
public ActionResult Index()
{
return View();
}
[HttpGet]
public JsonResult GetTimeDifference(string location)
{
DateTime utc = DateTime.UtcNow;
string timeZoneName = GetTimeZoneName(location);
TimeZoneInfo gmt = TimeZoneInfo.FindSystemTimeZoneById("GMT Standard Time");
TimeZoneInfo local = TimeZoneInfo.FindSystemTimeZoneById(timeZoneName);
TimeSpan utcOffset = gmt.GetUtcOffset(utc);
TimeSpan localOffset = local.GetUtcOffset(utc);
TimeSpan difference = localOffset - utcOffset;
return Json(Convert.ToInt16(difference.TotalMinutes),JsonRequestBehavior.AllowGet);
}
}
The above code gives me a 404 Not Found Error:
Request URL:http://localhost:100/TimeDifference/GetTimeDifference?location=BVI&_=1511949514552
Request Method:GET
Status Code:404 Not Found
Remote Address:[::1]:100
If I use:
url: '#Url.Action("GetTimeDifference", "TimeDifference")'
The #Url.Action("GetTimeDifference", "TimeDifference") is Null so it doesn't go anywhere.
I have also tried:
#Html.Hidden("URLName", Url.Action("GetTimeDifference", "TimeDifference"))
...
url: $("#URLName").val()
Url is still Null.
I have added entries in to the Global.asax.cs for routing i.e.
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "TimeDifference", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
This doesn't seem to do anything.
I have gone through a lot of the questions raised previously and amended as per suggestions but nothing seems to work.
As I am new to this I'm sure it something very simple I am missing.
Many thanks,
HH
Your controller won't be wired automatically, and I don't think the global.asax.cs file will work either. You can either register a custom route for your controller in an Umbraco Startup Handler: https://our.umbraco.org/documentation/reference/routing/custom-routes or you can create your controller as an Umbraco WebApi Controller, which is designed for stuff like this: https://our.umbraco.org/documentation/Reference/Routing/WebApi/.
Umbraco WebAPI controllers get wired in automatically and will return either JSON or XML automatically depending on what the calling client asks for.

Calling partial view through AJAX in Asp.net MVC 5

I'm using the following code to call a partial view:
$('#btnGetMilestones').click(function () {
$.ajax({
url: "GetMilestones",
type: "get",
success: function (result) {
$('#milestonesContainer').html(result);
},
error: function (xhr, status, error) {
var msg = "Response failed with status: " + status + "</br>"
+ " Error: " + error;
$('#milestonesContainer').html(msg);
},
complete: function (xhr, status) {
var doneMsg = "Operation complete with status: " + status;
alert(doneMsg);
}
});
});
for this ActionResult:
public PartialViewResult GetMilestones()
{
return PartialView("_GetMilestones");
}
The partial view has the milestones for a project (milestones and project are models). When I call the partial view like this:
<div id="milestonesContainer">
#Html.Partial("_GetMilestones")
</div>
it works fine, it gets all the milestones for the project.
But when I try to call the partial view via ajax, the error gets called: Response failed with status: error
Error: Bad Request
I'm in the details view of a projects so the url is like this http://localhost:55623/Projects/Details/2002
I'm new in ajax and javascript, so please if possible, explain me like you do to a beginner.
UPDATE:
After getting some answer and playing around to find a solution, I understand why the error appears.
I'm inside the details view, so the url is like this: http://localhost:55623/Projects/Details/2002 see there is an ID parameter.
When I make the ajax call, the url is like this http://localhost:55623/Projects/Details without the id parameter. So in return I get a 400 error code
To build on my comment:
Sorry, I was being ambiguous with the term url. Here's what I meant:
Unless your currentl url in the browser is http://<hostname>/<Controller that contains GetMilestones>, your AJAX url is incorrect. The AJAX url needs to be /<Controller>/GetMilestones.
The beginning / takes you to the root of the project, then the rest is taken care of by your route config (typically /Controller/Method/Id). That's why the AJAX url usually needs to be /Controller/Method. However, if you are at the Index view, your url is typically http://<hostname>/Controller. So, if this is the case and your AJAX url is just Method, it will take you to http://<hostname>/Controller/Method since you didn't prepend your AJAX url with a /.
Instead of url: "GetMilestones", try using url: "#Url.Action("GetMilestones")" which will render the actual relative path of the action i.e. /{Controller}/GetMilestones.
Also ensure that you are referring to the correct file name in your controller, as in your view you refer to "_GetMilestone" and you say that works, but in your controller you reference "_GetMilestones" which would not resolve if your filename is indeed "_GetMilestone"
If you're getting a 500 error, that means it's likely that you're hitting the action and an exception is occurring before or while it renders the partial view. Try navigating directly to the partial view's action in your browser by typing localhost:port/Projects/GetMilestones and see if an exception page appears. Make sure you do something like this in the Configure method of your Startup class:
public void Configure (IApplicationBuilder app)
{
app.UseDeveloperExceptionPage();
}
You should consider taking advantage of the helper methods like Url.Action to generate the correct relative path to the action method you want to call via ajax. If you are js code is inside the view, you can simply call the method like
url: "#Url.Action("GetMilestones","Project")",
If it is in an external js file, you can still use the helper method to generate the path and set it to a variable which your external js file. Make sure to do javascript namespacing when you do so to avoid possible overwriting of js global variables.
so in your view/layout you can do this
<script>
var myApp = myApp || {};
myApp.Urls = myApp.Urls || {};
myApp.Urls.mileStoneUrl= '#Url.Action("GetMilestones","Project")';
</script>
<script src="~/Scripts/PageSpecificExternalJsFile.js"></script>
And in your PageSpecificExternalJsFile.js file, you can read it like
$(function(){
$('#btnGetMilestones').click(function () {
$.ajax({
url: myApp.Urls.mileStoneUrl,
//Your existing code goes here
})
});
});
You need to change first url to something that match the route:
'/<Controller>/GetMilestones/'
switch from PartialViewResult to ActionResult
go for ajax like:
url: "GetMilestones",
type: "get",
contentType: 'application/html; charset=utf-8',
dataType : 'html'
Thanks to all for answering. I got an answer for my problem, maybe it's kinda not expected. Her it is:
change the ajax method:
$('#btnGetMilestones').click(function () {
$.ajax({
url: '/Projects/GetMilestones/' + "?id=" + window.location.href.split('/').pop(),
type: "GET",
success: function (data) {
$('#milestonesContainer').html(data);
},
error: function (xhr, status, error) {
var msg = "Response failed with status: " + status + "</br>"
+ " Error: " + error;
$('#milestonesContainer').html(msg);
},
complete: function (xhr, status) {
var doneMsg = "Operation complete with status: " + status;
alert(doneMsg);
}
});
});
and the action result:
public ActionResult GetMilestones(int? id)
{
var forProject = db.Projects.Where(x => x.ID == id).SingleOrDefault();
return PartialView("_GetMilestones",forProject);
}
Or same action result but the ajax request slightly dirrent:
$('#btnGetMilestones').click(function () {
var id;
id = #Model.ID;
$.ajax({
url: '/Projects/GetMilestones',
type: "GET",
data: "id="+id,
success: function (data) {
$('#milestonesContainer').html(data);
},
error: function (xhr, status, error) {
var msg = "Response failed with status: " + status + "</br>"
+ " Error: " + error;
$('#milestonesContainer').html(msg);
},
complete: function (xhr, status) {
var doneMsg = "Operation complete with status: " + status;
alert(doneMsg);
}
});
});

Multiple AJAX requests in MVC3 application

The situation, I'm making multiple ajax/json requests on the same page to a controller, which returns a JsonResult.
I know this is a problem with the session state, I've added the [SessionState(SessionStateBehavior.Disabled)] attribute on my controller class, but nothing seems to work, my second ajax request just wont get the return data.
the controller:
[SessionState(SessionStateBehavior.Disabled)]
public class IndexController : Controller
{}
the two json methods:
[AcceptVerbs(HttpVerbs.Get)]
public JsonResult GetLatestListJSON()
{
Thread.Sleep(5000);
ArticleRepository repo = new ArticleRepository();
IList<ArticleModel> list = repo.GetLatestContent(10);
return Json(list, JsonRequestBehavior.AllowGet);
}
[AcceptVerbs(HttpVerbs.Get)]
public JsonResult GetCustomerJSON()
{
Thread.Sleep(5000);
CustomerRepository Repo = new CustomerRepository();
IList<Customer> cust= Repo.GetCustomer();
return Json(cust, JsonRequestBehavior.AllowGet);
}
The second ajax call, the other one is very similar, I never get to see the 'succes'-alert.
<script type="text/javascript">
$(document).ready(function () {
alert('before');
$.getJSON("/Index/GetCustomerJSON", null, function (data) {
alert('succes');
$("#loadingGifVideo").hide();
$.each(data, function (index, mod) {
});
});
});
Thanks guys :)
If you put a break-point in your GetCustomerJSON method and run this in Visual Studio does the method ever get called? It does
EDIT
Try switching from getJSON to the ajax method so you can capture any errors. Like so:
$.ajax({
url: "/Index/GetCustomerJSON",
dataType: 'json',
data: null,
success: function (data) { alert('success'); }
error: function (data) { alert('error'); }
});
Do you get an "error" alert?

jQuery Autocomplete throws 401 - Unauthorised error while calling MVC 3 controller action method

I am getting "401 - Unauthorised" error in jQuery Autocomplete control in MVC3 application (.net framework v4.0.30319) which is deployed on a server containing IIS 7.5
Controller: (SearchSuggestController)
[HttpGet]
public JsonResult SuggestByEmployeeId(string Id)
{
var suggestions = from a in Context.Employees
where a.EmployeeId.Contains(Id)
select new
{
a.EmployeeId,
a.FirstName,
a.LastName
};
return Json(suggestions, JsonRequestBehavior.AllowGet);
}
jQuery: (Autocomplete)
$(function () {
$("#IDFilter").autocomplete({source: function (request, response) {
$.ajax({
url: "/SearchSuggest/SuggestByEmployeeId",
type: "POST",
dataType: "json",
data: { Id: request.term },
error: function (XMLHttpRequest, status, error) {
alert("Error status:(" + status + ") error:(" + error + ")");
},
success: function (data) {
response($.map(data, function (item) {
return { label: item.EmployeeId, value: item.EmployeeId,id: item.EmployeeId };
}));
}
});
},
minLength: 3,
autoFocus: true,
select: function (event, ui) {
$("#IDFilter").val(ui.item.value);
}
});});
jQuery is calling url: "/SearchSuggest/SuggestByEmployeeId" i.e. SearchSuggest controller's
SuggestByEmployeeId action.
Search.cshtml:(View)
#using (Html.BeginForm("BasicSearch", "Employee"))
{
#Html.Label("Employee Id:")
#Html.TextBox("IDFilter")
<input type="submit" value="Search" />
}
BasicSearch action method in Employee controller is working fine if valid EmployeeID is entered in "IDFilter" and clicked on Search button.
Autocomplete is showing expected results when i run the code through visual studio IDE. After publishing and Bin Deploying of this code to IIS 7.5 is throwing 401-Unauthorized error. The application is hosted under Default Web Site in IIS.
Anybody has any idea what is going wrong here?
You are AJAX POST to the action, but your action only accepts GET ?
Does your controller (or base controller) have the [Authorize] attribute?
I think i have got a solution.
Digging into jQuery using IE8 Developer Tools
On host server, the autocomplete XMLHttpRequest is trying to search for Request URL "http://localhost:80/SearchSuggest/SuggestByEmployeeId?Id=123"
But my application is hosted as "MyApp" under Default Web Site, so the URL should be like "http://localhost:80/MyApp/SearchSuggest/SuggestByEmployeeId?Id=123"
Hence i have updated the URL to url: "/MyApp/SearchSuggest/SuggestByEmployeeId"
After this change Autocomplete is fetching the expected results. 401 error is gone.
Probably in host environment, i will have to setup a new web site and bin deploy my MVC application under that.
This way i don't need to make this modification in jQuery everytime.
If anyone has got a better solution, please suggest.
To avoid issues with relative paths, rather than hard-coding the URL, use the #URL.Action helper.
So, your old code: url: "/SearchSuggest/SuggestByEmployeeId",
should become: url: '#Url.Action("SuggestByEmployeeId", "SearchSuggest")'
Good luck!

Resources