Fire a controller action from a jQuery Autocomplete selection - asp.net

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;
}

Related

MVC 5 JsonResult returns html?

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.

Extract Div from returned view

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;
});
});

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);.

jquery Post does not work in asp.net mvc 3?

I just copied some code from an asp.net mvc 2 app which works. Now i am trying it in asp.net mvc 3 and it does not call the save method on the controller?
controller:
[HttpPost]
public JsonResult save(string inputdata)
{
return Json(new { Result = string.Format("From the controller - you have clicked the GO-button ! ") }, JsonRequestBehavior.AllowGet);
}
view:
<button id="but">go</button>
<div id=result></div>
<script type="text/javascript">
$(document).ready(
$("#but").click(
function () {
$.ajax({
url: "/Home/save",
dataType: "json",
type: 'POST',
data: "test",
success: function (result) {
$("#result").html(result.Result);
}
});
}
)
);
</script>
You are not passing the data correctly. The action argument is called inputdata. So you should use this same name in the data hash of the AJAX request:
$.ajax({
url: '/Home/save',
dataType: 'json',
type: 'POST',
data: { inputdata: 'test' },
success: function (result) {
$('#result').html(result.Result);
}
});
Also never hardcode urls in your javascript, always use url helpers or your application will simply stop working when you deploy due to the possibility of having a virtual directory name:
$.ajax({
url: '#Url.Action("save", "home")',
dataType: 'json',
type: 'POST',
data: { inputdata: 'test' },
success: function (result) {
$('#result').html(result.Result);
}
});
Another issue that you have with your code is that you are not canceling the default action of the button meaning that if this is an action link or a submit button the AJAX request might never have the time to execute before the browser redirects.
Also you don't need to specify the dataType to JSON as jQuery is intelligent enough to deduce this from the Content-Type response header sent from the server.
So the final version should look something along the lines of:
<script type="text/javascript">
$(function() {
$('#but').click(function () {
$.ajax({
url: '#Url.Action("save", "home")',
type: 'POST',
data: { inputdata: 'test' },
success: function (result) {
$('#result').html(result.Result);
}
});
return false;
});
});
</script>

JQuery AutoComplete updating multiple fields ASP.NET

I'm trying to use the AutoComplete feature of JQuery to update multiple fields on an ASP.NET web page. The individual textbox is functioning perfectly, but I cannot figure out how to update multiple textboxes on the page once the user selects.
I've read many suggestions here that state I need to implement a result handler, but my intellisense is not showing that as an option, and IE I get a JS error saying that the object doesn't support this method.
I am linking to jquery-1.4.2.min.js and jquery-ui-1.8.5.custom.min.js
Here's my code:
$(function () {
$("#Street1").autocomplete({
source: function (request, response) {
$.ajax({
url: "/address/FindAddress", type: "POST", dataType: "json",
data: { startAddress: request.term },
success: function (data) {
response($.map(data, function (item) {
return { label: item.DisplayText, value: item.ValueText, id: item.ID }
}))
}
})
} /* End source: function */
})
.result(function (event, data, formatted) {
$("#Street2").val("test");
})
/* end Autocomplete */
}); /* Function */
In this case you'd want the select handler, like this:
$("#Street1").autocomplete({
source: function (request, response) {
$.ajax({
url: "/address/FindAddress", type: "POST", dataType: "json",
data: { startAddress: request.term },
success: function (data) {
response($.map(data, function (item) {
return { label: item.DisplayText, value: item.ValueText, id: item.ID }
}));
}
});
},
select: function( event, ui ) {
$("#Street2").val(ui.item.label); //or ui.item.value
}
});
I'm not sure if you want the label, value or id in there, just use ui.item.whatever. Using select, whatever a value is chosen you can populate the #Street2 field as well.
view the source of this example, it's exactly what you want (look at the select method) : http://jqueryui.com/demos/autocomplete/#custom-data
Also, it's JavaScript, don't rely on intellisense.
EDIT: I pasted the wrong link

Resources