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")
Related
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.
I have a form that assembles sections of a larger form. For example:
Html.RenderPartial("Partials/MealPreference", Model);
I would like to dynamically add sections to the form. Given the nature of my partial views, I must pass the model along as well. In that, I am failing miserably.
The markup on my containing page:
<div id="additionalPreference"></div>
<input type="button" value="Add Additional Preference" id="addPreference" />
<script>
$(document).ready(function () {
$('#addPreference').click(function () {
$.ajax({
type: "POST",
url: '#Html("AddPreference", "Main")',
success: function (html) {
$(html).appendTo('#additionalPreference');
console.log(html);
},
error: function (xhr, ajaxOptions, thrownError) {
alert("Error");
},
complete: function () {
console.log("End");
}
});
});
});
</script>
My controller action:
[HttpPost]
public ActionResult AddPreference(FormViewModel model)
{
if (ModelState.IsValid)
{
return PartialView("Partials/AdditionalPreference", model);
}
else
{
return PartialView("Partials/LoadFailed");
}
}
The model is never valid. How do I pass the model form the containing page to the controller action? This would seem to be something simple to do (it certianly would be in Web Forms) but I have been choking on this for 3 hours.
For an ajax call you have to build the model:
$.ajax({
type: "POST",
url: '#Url.Action("AddPreference", "Main")',
data: {
Field1: 'field1',
Field2: 'field2'
},
success: function (html) {
$(html).appendTo('#additionalPreference');
console.log(html);
},
error: function (xhr, ajaxOptions, thrownError) {
alert("Error");
},
complete: function () {
console.log("End");
});
Make sure that the names in the data section of the ajax call match exactly the names in your model and it should show up in your controller populated.
update:
Since writing this answer I have learned more about sending information back to the controller via ajax. As commented by Rick Dailey you can send the model submitted to the form back to the controller via:
#Html.Raw(Json.Encode(Model))
I have found out about serialize and we use:
$('form').serialize()
To send the fields on the form back to the controller. A quick, easy way to send all information back similar to a post back without having to manually build the model.
You need to add the properties of the model for the controller you are calling in the ajax request. In this case your AddPreferencecontroller has a parameter of type FormViewModel. I assume the information for the FormViewModel is stored on the page. You need to pass those in the data property for the ajax request.
If you post your FormViewModel properties I could help futher. Bascially you need to the following:
$('#addPreference').click(function () {
$.ajax({
type: "POST",
url: '#Html("AddPreference", "Main")',
data: {id: "123asd", Prop1: myProp1},
success: function (html) {
$(html).appendTo('#additionalPreference');
console.log(html);
},
error: function (xhr, ajaxOptions, thrownError) {
alert("Error");
},
complete: function () {
console.log("End");
}
});
Post more information of your model and the view you are making the ajax request and I can assist further.
I an working on returning view from controller to jquery ,View is returned but i want to extract div from returned view.My Current code is like this
public ActionResult DeleteItem(int pid)
{
//my logic goes here
retutn View("SomeView",model);
}
Jquery
enter code here
script type="text/javascript">
$(document).ready(function () {
$('.Remove').click(function () {
var value = $(this).attr('id');
$.ajax({
cache:true,
type: "POST",
url: "#(Url.Action("DeleteItem", "ControllerName"))",
data: "pid=" + value,
success: function (data) {
$("body").html(data);
},
error:function (xhr, ajaxOptions, thrownError){
alert('Failed to subscribe.');
},
complete: function() { }
});
return false;
});
});
</script>
My current logic returns view and assign total view i.e html+body to body part of page ,which shows html part two times.Is there any way to retrieve div from the returned view and reload it.
thanx in advance
Your controller action should return a PartialViewResult otherwise it will return your layout page in the response. If you want to cater for both scenarios you can check whether the request is an AJAX request:
public ActionResult DeleteItem(int id) {
// delete your item
if (Request.IsAjaxRequest()) {
// return just the partial view
return PartialView("yourview");
}
// otherwise handle normally
return RedirectToAction("list");
}
To understand the difference between returning View and returning PartialView please see What's the difference between "return View()" and "return PartialView()".
script type="text/javascript">
$(document).ready(function () {
$('.Remove').click(function () {
var value = $(this).attr('id');
$.ajax({
cache:true,
type: "POST",
url: "#(Url.Action("DeleteItem", "ControllerName"))",
data: "pid=" + value,
success: function (data) {
var t=$(data).find('.divtoreplacewith');
$('.divtoreplace').replaceWith(d);
//Wasted my 2 days for above two lines.But satisfied with solution,
//Both div are same but '.divtoreplacewith' is having new data,And I have replaced div with that div that's all
},
error:function (xhr, ajaxOptions, thrownError){
alert('Failed to subscribe.');
},
complete: function() { }
});
return false;
});
});
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);.
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;
}