MVC 5 JsonResult returns html? - asp.net

I have been following this tutorial https://www.youtube.com/watch?v=c_MELPfxJug regarding ajax and JsonResult in HomeController
I did the tutorial, however for some reason the controller is returning Html and not json
I did not change one line of code, but it's failing with parseError on the javascript side.
when i look at the response i see an html page, not a json object.
Controller code:
public JsonResult DoubleValue(int? Value)
{
if (!Request.IsAjaxRequest() || !Value.HasValue)
{ return null; }
else
{
int DoubleValue = Value.Value * 2;
var ret = new JsonResult
{
Data =
new { DoubleValue = DoubleValue }
};
return ret;
}
}
cshtml:
#using (Html.BeginForm())
{
#Html.TextBox("txtAmount",0)
<button id="btnDoubleValue">DoubleIT</button>
<div id="lblMessage"></div>
}
#section Scripts{
<script type="text/javascript">
$(function () {
$('#btnDoubleValue').on('click', function() {
$.ajax({
type: 'POST',
url: '#Html.Action("DoubleValue")',
data: { 'Value': $('#txtAmount').val() },
datatype: 'json',
cache: 'false'
}).success(function (data) {
var t = data;
$('#txtAmount').val(data.DoubleValue);
}).error(function (x, o, e) {
$('#lblMessage').html('error was found: ' );
});
return false;
})
});
</script>
}

found the error
I was using Html.Action and not Url.Action -> just human error I suppose
from the reference:
Html.Action - returns the result as an HTML string.
It works now
$.ajax({
type: 'POST',
url: '#Url.Action("DoubleValue")', //<--- Url.Action
data: { 'Value': $('#txtAmount').val() },
datatype: 'json',
cache: 'false'

I guess this must be the default error page, you are probably getting a 500 response and you must use the Network tab of your browser to see the real problem.
In your browser open developer tools using F12 key and navigate to Network tab.
Make the appropriate actions to do the ajax request (click on that button)
Click on the request row
Navigate to Response tab.
From there you can watch the real request your ajax does and the response from the server.

Related

View not loaded when ActionResult is called from AJAX in ASP.NET MVC

I have called actionresult function from JavaScript using AJAX when a button is clicked:
<script type="text/javascript">
$('.btn-SelectStudent').on('click', function () {
$('input:radio').each(function () {
if ($(this).is(':checked')) {
var id = $(this).val();
$.ajax({
url: '#Url.Action("ParseSearchLists", "Upload")',
data: { studentId: id }
}).success(function (data) {
alert('success');
});
}
else {
// Or an unchecked one here...
}
});
return false;
})
</script>
Inside the UploadController.cs:
[HttpPost]
public ActionResult ParseSearchLists(int studentId)
{
SearchModel searchModel = ApplicationVariables.searchResults.Where(x => x.StudentId == studentId).ToList().First();
TempData["SearchModel"] = searchModel;
return RedirectToAction("UploadFile", "Upload");
}
public ActionResult UploadFile()
{
searchModel = TempData["SearchModel"] as SearchModel;
return View(searchModel); //debug point hits here.
}
Inside UploadFile(), I have returned View and it should load another view. But I get only "success" in alert but no new view is loaded. I assume, view should be loaded.
You're making an "AJAX" call to the server, meaning your request is running outside of the current page request and the results will be returned to your success continuation routine, not to the browser's rendering engine. Essentially the data parameter of that routine is probably the entire HTML response of your UploadFile view.
This is not what .ajax is used for. It is for making asynchronous requests to the server and returning data (usually JSON or XML) to your javascript to be evaluated and displayed on the page (this is the most common use anyway).
I can't see your HTML, but wouldn't you be better off just using an <a> anchor (link) tag and sending your student ID on the query string? It's hard to tell what you are attempting to do but your views' HTML (.cshtml) will never be displayed using the code you have now.
It seems, you are not loading view returned to div on ajax success. replace #divname with your div in your code in below code. i hope this helps to resolve your issue
<script type="text/javascript">
$('.btn-SelectStudent').on('click', function () {
$('input:radio').each(function () {
if ($(this).is(':checked')) {
var id = $(this).val();
$.ajax({
url: '#Url.Action("ParseSearchLists", "Upload")',
dataType: "html",
data: { studentId: id }
}).success(function (data) {
$('#divName').html(data); // note replace divname with your actual divname
});
}
else {
// Or an unchecked one here...
}
});
return false;
})
</script>
[HttpPost]
public ActionResult ParseSearchLists(int studentId)
{
SearchModel searchModel = ApplicationVariables.searchResults.Where(x => x.StudentId == studentId).ToList().First();
return View("UploadFile",searchModel); //debug point hits here.
}

HttpResponseMessage Headers.Location Seemingly Being Ignored

I have the following Web Api method, which works fine as far as creating a new product and setting the location. I know this because I check the response header in Google developer tools and see that it is valid. If I cut and paste the location from tools to the browser, the page loads fine. However, it will not load as a result of returing the response from the method.
public HttpResponseMessage PostProduct(Product product)
{
productsRepository.Create(product);
var response = Request.CreateResponse<Product>(HttpStatusCode.Created, product);
string uri = Url.Link("ProductsIndex", null);
response.Headers.Location = new Uri(Request.RequestUri,"/Products/testview");
return response;
}
The jQuery that calls PostProduct:
$("#createjQButton").click(function () {
var product = { Name: $("#Name").val(), Category: $("#Category").val(), Price: $("#Price").val() };
var json = JSON.stringify(product);
// Send an AJAX request to create a new product
$("#createjQButton").click(function () {
var product = { Name: $("#Name").val(), Category: $("#Category").val(), Price: $("#Price").val() };
var json = JSON.stringify(product);
$.ajax({
url: '/api/productsapi',
cache: false,
type: 'POST',
data: json,
contentType: 'application/json; charset=utf-8'
});
return false;
});
Why is the location being ignored?
Well, I added
statusCode: {
201 : function() {
window.location.replace("/Products/testview");
}
to my jQuery click function and got to the desired page that way. But should not the original way have worked?

Viewdata not showing in partial view

Hi guys i have controller which returns a partial view, the controller is called by ajax script. The partical view has no problem showing viewdata first time, But when ajax script is invoked second time the partical view does not update it self with new viewdata.
code for controller
[HttpGet]
public ActionResult getPart(int id)
{
ViewData["partical"] = id;
return PartialView("test");
}
code for partial view
<%# Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<PovertyBayHotel.Models.testmodel>" %>
<p>just a test</p>
<%: ViewData["partical"]%>
and the ajax which call the controller
<script type="text/javascript">
$(document).ready(function () {
$("#DropDown").change(function () {
var course = $("#DropDown > option:selected").attr("value");
$.ajax({
type: 'GET',
url: '/Reservation/getPart',
data: { id: course },
success: function (data) {
$('#ExtraBox').replaceWith(data);
}
});
});
});
</script>
Might be a caching issue. Try HTTP POST instead of GET or set the ifModified and cache options to false as below:
$("#DropDown").change(function () {
var course = $("#DropDown > option:selected").attr("value");
$.ajax({
type: 'GET',
ifModified: false,
cache: false,
url: '/Reservation/getPart',
data: { id: course },
success: function (data) {
$('#ExtraBox').replaceWith(data);
}
});
Also, try to debug your code and see really what is going on.
Edit:
The problem has been solved by changing $('#ExtraBox').replaceWith(data); with $('#ExtraBox').html(data);.

Ajax success when a view is returned

I'm struggling to return a view or partial view with Ajax. Whenever I change the return type to something that isn't JSon the ajax command never succeeds. I need to return a partial view because I want to return a lot of data back.
This is my current code:
(Controller)
[HttpPost]
public ActionResult AjaxTestController(string Input)
{
string Results = Input + " -- TestTestTest";
return PartialView("Test", Results);
//return new JsonResult() { };
}
(View)
function AjaxTest() {
alert("test");
$.ajax({
type: "POST",
url: "Home/AjaxTestController",
data: "Input=Test11111",
success: function () {
alert("Success!");
}
});
Thanks!
You can use the $.post command for that:
function AjaxTest() {
alert("test");
$.post({
url: "Home/AjaxTestController",
data: "Input=Test11111",
success: function (response) {
alert(response);
}
});
try the following:
$(function () {
$('#submit').live('click', function () {
AjaxTest();
});
});
function AjaxTest() {
$.ajax({
type: "POST",
url: '#Url.Action("AjaxTestController", "Home")',
data: { Input: "Test - " + new Date() },
success: function (data) {
$('#partialResult').html(data);
},
error: function (xhr, err) {
alert(xhr.responseText);
}
});
};
inside your view and ensure that you have your target div set up for the partial to be populated into:
<div id="partialResult"></div>
also, for the example above, I added a button to the view to initiate the ajax (purely for testing):
<input type="button" value="Submit" id="submit" />
your 'partialview' should look something like this:
#model string
<h2>
Partial Test</h2>
<p>
#Model
</p>
no other changes are required to the existing action for this to now function as required.
[UPDATE] - I changed the AjaxTest() method to include the error event (the result of which is captured in an alert). hopefully, this may help further.
partial View is different than view you have to specify the whole path to the partial view or have it in share folder. otherwise is going to return not found and never success. any way this always work for me, try
partialView("~/Views/ControllerView/Test.cshtml")

Fire a controller action from a jQuery Autocomplete selection

I have a jQuery autoselect box displaying the correct data. Now I would like to fire an ASP.NET MVC 3 controller when an item is selected. The controller should then redirect to a View. Here's my jQuery autocomplete code (I'm sure something is missing in the 2nd Ajax call, but I haven't found it yet):
<script type="text/javascript">
$(function () {
$("#Client").autocomplete({
source: function (request, response) {
$.ajax({
url: 'Entity/GetClientAutoComplete', type: 'POST', dataType: 'json',
data: { query: request.term },
success: function (data) {
response($.map(data, function (item) {
return { label: item, value: item };
}))
}
})
},
minLength: 1,
select: function (event, ui) {
$.ajax({
url: 'Entity/GetApplicationsByName/' + ui.item.value, type: 'POST'
})
}
});
});
</script>
And here's the controller I'm trying to call:
public ActionResult GetApplicationsByName(string id)
{
ViewBag.Client = id;
var apps = _service.GetDashboardByName(id);
return View("Dashboard", apps.ToList());
}
When I watch the Ajax call fire in Firebug, I see the correct URL configuration, but nothing else happens. It's acting as though it wants to load something rather than send something. I'm confused. Thank you for any guidance.
Well you sent an id by POST to the GetApplicationsByName controller and the controller is sending back the view.
If you want redirection, you can use the following:
select: function (event, ui) {
window.location.href = 'Entity/GetApplicationsByName/' + ui.item.value;
}

Resources