when i am using Request.IsAjaxRequest(). i am not able to return view(). please check below code.
this is Action.
public ActionResult Index()
{
if (!Request.IsAjaxRequest()) {
return View("ajexview");
}
return view("About");
}
this is view
<script>
$(function () {
$("button").click(function () {
var car = { Make: 'Audi', Model: 'A4 Avant', Color: 'Black', Registered: 2013 };
$.ajax({
type: "POST",
url: "/home/index/",
data: car,
datatype: "html",
success: function (data) {
$('#result').html(data);
}
});
});
});
<button>Click me</button>
when i am posting about view is not able to return
First off, i'm not sure if your Index action will be hit by your ajax call at all. You are doing a post against a get action. To get the Request.IsAjaxRequest() to work as intended, either try creating another controller action and marking it with the HttpPost attribute like so,
[HttpPost]
public ActionResult Index(Car car)
{
if (!Request.IsAjaxRequest()) {
return PartialView("ajexview");
}
return View("About");
}
Note also that in the if (!Request.IsAjaxRequest()) block i'm returning "ajexview" as a PartialView.
or if your intention was to hit the get Index action then you will need to do an ajax 'get' request instead like
$.ajax({
type: "GET",
url: "/home/index/",
success: function (data) {
$('#result').html(data);
}
});
Be sure to Render scripts in the right place and order in your _layout.cshtml:
e.g. at the top:
...
<title>#ViewBag.Title</title>
#Styles.Render("~/Content/css")
#Scripts.Render("~/bundles/modernizr")
</head>
... and the bottom:
#Scripts.Render("~/bundles/jquery")
#Scripts.Render("~/bundles/jqueryval")
#Scripts.Render("~/bundles/bootstrap")
#Styles.Render("~/Content/datatables")
#Scripts.Render("~/bundles/datatables")
<!-- etc. -->
#RenderSection("scripts", required: false)
</body>
</html>
Also be mindful of the construction of your BundleConfig.cs.
Related
The autocomplete code written is getting the results from controller and is also showing when used F12 developer network tab with the browser. But the actual returned result is not showed by the textbox, only drop-down with no values are shown.
I'm including the codes of view and controller. Please help me out to solve this.
code of the view page :
<html>
<head><title></title>
<link href="~/Content/themes/base/jquery.ui.autocomplete.css" rel="stylesheet" />
<script type="text/javascript" >
$(document).ready(function () {
alert("hi");
$("#ValueField").autocomplete({
source: function (request, response) {
$.ajax({
url: "/Customer/AutoretrieveCustomer",
type: "POST",
dataType: "json",
data: { term: request.term },
success: function (data) {
var items = $.map(data, function (item) {
return {
label: item.FirstName,
value: item.FirstName
};
});
response(items);
}
})
}
});
});
</script>
</head>
<body>
<div id="CusView">
<label for="FirstName">Enter Customer First name : </label>
Enter value : <input type="text" id="ValueField" />
</div>
</body>
</html>
code of the controller :
[AcceptVerbs(HttpVerbs.Post)]
public JsonResult AutoretrieveCustomer(string term)
{
Banking.BankingDBEntities db = new BankingDBEntities();
var suggest = from s in db.Customers
select s.FirstName;
var namelist = suggest.Where(n => n.ToLower().StartsWith(term.ToLower()));
return Json(namelist, JsonRequestBehavior.AllowGet);
}
Also I would need the code for getting the id of the user selected item in the textbox.
The following the output pic when the autocomplete is executed
This bit in your controller action:
var suggest = from s in db.Customers
select s.FirstName;
var namelist = suggest.Where(n => n.ToLower().StartsWith(term.ToLower()));
Means that your controller action is actually returning an array of strings, not an array of objects like your success function is assuming.
You should be able to remove the mapping and just call response directly with the array of strings:
success: function (data) {
response(data);
}
Or, just:
success: response
I am going following steps:
in the controller action no.1 redirect to view no1;
in view no.1 I want to display cshtml page and next I want to redirect to the new action no.2 by using
#{Response.Redirect(Url.Action("CreatePdf", "Home");}
directive;
Action no.2 is reached and I've got my result (pdf file) but I can;t see the view no.1 from which I've called this action.
How can I load this view and display html page?
Just a little tweak to #DavidG's answer:
<script type="text/javascript">
$(document).ready(function () {
setTimeout(DownloadPdf, 1000);
});
function DownloadPdf() {
location.href = "#Url.Action("CreatePdf", "Home")";
}
</script>
Just tested and working. It will download the file after 1sec
A redirect causes the entire session to be directed to the new page ans loses anything you have sent out. I would use jQuery instead:
<script type="text/javascript">
$(document).ready(function () {
setTimeout(DownloadPdf, 1000);
});
function DownloadPdf() {
window.location = "#Url.Action("CreatePdf", "Home")";
}
</script>
I would suggest :
public ActionResult ControllerAction1()
{
return View();
}
For the View(), for document.ready function :
$(document).ready(function () {
$.ajax({
url: '#Url.Action("Action2", "Controller")',
contentType: 'application/json; charset=utf-8',
type: 'POST',
dataType: 'html',
data: JSON.stringify(model)
})
.success(function(result) {
// return true or false
// html of json result
})
.error(function(xhr, status) {
});
});
How can i change page in browser, after end of controller?
I tryed this:
Html/JS code:
<form>
<button type="submit" onclick="abc()">123</button>
</form>
<script>
function abc()
{
$.post("/", "abc", function () {
});
}
</script>
ASP.NET MVC Code:
[HttpPost]
public ActionResult Index(dynamic response)
{
return Redirect(Request.UrlReferrer.ToString() + "/Home/OtherPage");
}
What am I doing wrong?
[HttpPost]
public ActionResult Index(dynamic response)
{
return RedirectToAction("OtherPage", "Home");
}
Check this solution -
Your Action should be like this -
public ActionResult RedirectMe()
{
return new JsonResult() { Data = "http://www.google.com", JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}
Then your JQuery POST should be -
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script>
function submitForm() {
jQuery.ajax({
type: "POST",
url: "#Url.Action("RedirectMe")",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data) {
window.location.href = data;
},
failure: function (errMsg) {
alert(errMsg);
}
});
}
</script>
<input type="button" value="Click" onclick="submitForm()" />
When you Click the button, you will be redirected to the Google. You have to make sure you construct a proper URL (instead of google) and send it back.
If you want to pass some parameters to Action, then follow this way -
public ActionResult RedirectMe(string id)
{
return new JsonResult(){ Data = "http://www.google.com", JsonRequestBehavior = JsonRequestBehavior.AllowGet};
}
Finally your JQuery POST should be -
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script>
function submitForm() {
jQuery.ajax({
type: "POST",
url: "#Url.Action("RedirectMe")",
dataType: "json",
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ id: "This is my parameter"}),
success: function (data) {
window.location.href = data;
},
failure: function (errMsg) {
alert(errMsg);
}
});
}
</script>
<input type="button" value="Click" onclick="submitForm()" />
If you want to redirect to another page in your client code, You may send the new url in a JSON response and use window.location.href property to naviagate to that.
[HttpPost]
public ActionResult Index(dynamic response)
{
//Do your other work
string newUrl=Request.UrlReferrer.ToString() + "/Home/OtherPage";
//It may be better to use the Helper methods to get the url.
return Json(new { NewUrl=newUrl);
}
In your ajax call
$.post("YourURLHEre",{ response :YourDataHere},function(res){
window.location.href=res;
});
How to return another view of the same controller? I made some debugging for the application: the ajax method calls the controller action, pass the parameter, executes the instructions. At the
return View("GetEmployeeDays", model);,
the "GetEmployeeDays" view receives the values from model and is populated, but finally in the browser I receive the initial view (from I made the request) - not the GetEmployeeDays view
routing code from Global.asax:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
}
JQuery code that calls the action controller's and pass a parameter:
<script type="text/javascript">
$(document).ready(function () {
$('li').click(function () {
$.ajax({
url: '#Url.Action("GetEmployeeDays", "ApproveWork")',
type: 'GET',
dataType: 'json',
contentType: 'application/json; charset=utf-8',
data: { userCode: $(this).attr('id') }
})
});
});
Controller action that should render the GetEmployeeDays view:
[HttpGet]
public ActionResult GetEmployeeDays(string userCode)
{
.....
return View("GetEmployeeDays", model);
}
If you want to simply load something to a part of your page without reloading to a new page, you should update the specific part of your page in the callback of your ajax function.
$(function(){
$('li').click(function () {
var uCode=$(this).attr("id");
$.get("#Url.Action("GetEmployeeDays","ApproveWork")?userCode="+uCode,
function(response){
$("#DivToBeUpdated").html(response);
});
});
});
If you want to redirect to a new view, you should do it by updating the location.href property value.
$(function(){
$('li').click(function () {
var uCode=$(this).attr("id");
var url="#Url.Action("GetEmployeeDays","ApproveWork")?userCode="+uCode;
window.location.href=url;
});
});
});
Without knowing what your original view is that is being re-rendered, I'd say that most likely your issue is that you should be returning this as a PartialView, since you are making an Ajax request. In addition, it doesn't look like you are actually rendering the result anywhere. What is your fiddler response? Does it show returned HTML? If it does, you probably just need to dump it onto the page by utilizing the .done callback within $.ajax.
<script type="text/javascript">
$(document).ready(function () {
$('li').click(function () {
$.ajax({
url: '#Url.Action("GetEmployeeDays", "ApproveWork")',
type: 'GET',
dataType: 'json',
contentType: 'application/json; charset=utf-8',
data: { userCode: $(this).attr('id') }
}).done(function() {
$(this).addClass("done");
});
});
</script>
You can't redirect via ajax request. Try a simple GET request:
<script type="text/javascript">
$('li').on('click', function()
{
document.location.href = '#Url.Action("GetEmployeeDays", "ApproveWork")' + '?param1=val1¶m2=val2';
});
</script>
The controller is fine as it is now.
EDITED: Updated as requested
?Building from #David Diez, you can append parameters to your request as follows:
<script type="text/javascript">
$('li').on('click', function()
{
document.location.href = '#Url.Action("GetEmployeeDays", "ApproveWork", new { caseSensativeParamName = "foo" })';
});
</script>
You can, of course, go a JavaScript route as well. Something like this should work:
<script type="text/javascript">
$('li').on('click', function()
{
var targetUrl = '#Url.Action("GetEmployeeDays", "ApproveWork")';
var yourParam = $("#input-id").val();
targetUrl = targetUrl + '?yourServerParamName=' + yourParam;
document.location.href = targetUrl;
});
</script>
Cheers.
I want to render the partial view using ajax.
When I submit the button, the partial view must be rendered.
I could implemented it using ActionLink but I want to call the Action by JavaScript.
But the following code doesn't work. The Action is called but the partial view does not be rendered.
View
#section script{
<script type="text/javascript">
function test() {
$.ajax(
{
type: "POST",
url: "Test",
data: "",
success: function (result) { alert("OK!!"); },
error: function (req, status, error) {
alert("Damn!!");}
});
}
</script>
}
<input type="submit" onclick="test()" />
<div id="Container">
Controller
public ActionResult Test()
{
if (Request.IsAjaxRequest())
{
return PartialView("ViewUserControl1");
}
return View();
}
Partial View ViewUserControl1
Hello world
This works but is not what I want to do
#Ajax.ActionLink("click me", "Test", new AjaxOptions { UpdateTargetId = "Container" })
Your url may not be correct. It dependent on your routing settings
defined in Global.asax . But usually your url should look like
"/Home/Test" if your action is in HomeController. It's better to use
url helper for getting actions' urls:
...
url: '#Url.Action("Test", "Home")'
...
You can render your partial in next way:
...
success: function (result) { $('#elementId').html(result) },
...
Also if you want to update block, don't forget to clear it first and if it contains form with unobtrusive validation - parse form.