Can't call new page by controller in Asp.net - c#

I want to call new page by click on a button by jQuery from Index.cshtml :
$("#btnSearch").click(function(){
var idser = $("#Name").val();
$.ajax({
type: "POST",
url: "/User/getAll",
id : idser,
success: function() {
alert("success");
}
});
});
});
It call to my controller action : UserController/getAll
[System.Web.Services.WebMethod]
public ActionResult getAll(string id,string name)
{
return View("AllUser");
}
But is still at Index.cshtml not go to AllUser.cshtml page? I don't know why...please help.
UPDATE :
my jquery function call my action in controller , and the action work correctly but it not return to AllUser.cshtml page.

Please check out the documentation here. I would attempt using a tag-helper in the Ajax setup like this:
$("#btnSearch").click(function(){
var idser = $("#Name").val();
$.ajax({
type: "POST",
url: '#Url.Action("User", "getAll", new { id = "ID", name = "searchName" })',
id : idser,
success: function() {
alert("success");
}
});
});
});

Firstly I don't know what is your purpose behind using ajax while your are redirecting the other page ?
But you if still want to use Ajax, you can achieve this by two ways:
1) you can assign window.location in your success block.
2) Use your code by following way :
$("#btnSearch").click(function(){
var idser = $("#Name").val();
$.ajax({
type: "GET",
url: "/User/getAll",
id : idser,
success: function() {
alert("success");
return true;
}
});
});
});
you can try it by putting return true in your script.
hope it helps to you

Updating in response to clarification in comments:
In the success callback,
location.href="/user/getall";
That will cause the browser to navigate to that URL after the ajax post has completed.
A button that posts a value from an input to another page - that's a form.
<form action="/User/getAll">
<input type="submit" value="Click me">
</form>
I don't know where your id is coming from, but you can put a hidden input in the form and a script to populate it (unless it's a user input - then you can just put the input right in the form.)
<form action="/User/getAll">
<input type="submit" value="Click me">
<input type="hidden" name="id" id="hiddenId"/>
</form>
<script>
$("#hiddenId").val($("#Name").val());
</script>
Or, if you want to be sure that your form's action URL matches your route:
<form action='#Url.Action("getAll", "User")'>
(Assuming that the controller is called "User".)

Here we go:
window.location.href = "yourUrl" can help you.
$("#btnSearch").click(function(){
var idser = $("#Name").val();
$.ajax({
type: "POST",
url: "/User/getAll",
id : idser,
success: function() {
alert("success");
window.location.href ="../yourUrl"; //This is working!
}
});
});
});
You may redirect in Controller this like:
[System.Web.Services.WebMethod]
public ActionResult getAll(string id,string name)
{
return RedirectToAction("NameOfAction"); //Here is going Name of Action wich returns View AllUser.cshtml
}
Hope it helps;)

Related

Using Action in Controller every 10min [duplicate]

I have sample code like this:
<div class="cart">
<a onclick="addToCart('#Model.productId');" class="button"><span>Add to Cart</span></a>
</div>
<div class="wishlist">
<a onclick="addToWishList('#Model.productId');">Add to Wish List</a>
</div>
<div class="compare">
<a onclick="addToCompare('#Model.productId');">Add to Compare</a>
</div>
How can I write JavaScript code to call the controller action method?
Use jQuery ajax:
function AddToCart(id)
{
$.ajax({
url: 'urlToController',
data: { id: id }
}).done(function() {
alert('Added');
});
}
http://api.jquery.com/jQuery.ajax/
Simply call your Action Method by using Javascript as shown below:
var id = model.Id; //if you want to pass an Id parameter
window.location.href = '#Url.Action("Action", "Controller")/' + id;
You are calling the addToCart method and passing the product id. Now you may use jQuery ajax to pass that data to your server side action method.d
jQuery post is the short version of jQuery ajax.
function addToCart(id)
{
$.post('#Url.Action("Add","Cart")',{id:id } function(data) {
//do whatever with the result.
});
}
If you want more options like success callbacks and error handling, use jQuery ajax,
function addToCart(id)
{
$.ajax({
url: '#Url.Action("Add","Cart")',
data: { id: id },
success: function(data){
//call is successfully completed and we got result in data
},
error:function (xhr, ajaxOptions, thrownError){
//some errror, some show err msg to user and log the error
alert(xhr.responseText);
}
});
}
When making ajax calls, I strongly recommend using the Html helper method such as Url.Action to generate the path to your action methods.
This will work if your code is in a razor view because Url.Action will be executed by razor at server side and that c# expression will be replaced with the correct relative path. But if you are using your jQuery code in your external js file, You may consider the approach mentioned in this answer.
If you do not need much customization and seek for simpleness, you can do it with built-in way - AjaxExtensions.ActionLink method.
<div class="cart">
#Ajax.ActionLink("Add To Cart", "AddToCart", new { productId = Model.productId }, new AjaxOptions() { HttpMethod = "Post" });
</div>
That MSDN link is must-read for all the possible overloads of this method and parameters of AjaxOptions class. Actually, you can use confirmation, change http method, set OnSuccess and OnFailure clients scripts and so on
If you want to call an action from your JavaScript, one way is to embed your JavaScript code, inside your view (.cshtml file for example), and then, use Razor, to create a URL of that action:
$(function(){
$('#sampleDiv').click(function(){
/*
While this code is JavaScript, but because it's embedded inside
a cshtml file, we can use Razor, and create the URL of the action
Don't forget to add '' around the url because it has to become a
valid string in the final webpage
*/
var url = '#Url.Action("ActionName", "Controller")';
});
});
Javascript Function
function AddToCart(id) {
$.ajax({
url: '#Url.Action("AddToCart", "ControllerName")',
type: 'GET',
dataType: 'json',
cache: false,
data: { 'id': id },
success: function (results) {
alert(results)
},
error: function () {
alert('Error occured');
}
});
}
Controller Method to call
[HttpGet]
public JsonResult AddToCart(string id)
{
string newId = id;
return Json(newId, JsonRequestBehavior.AllowGet);
}
You can simply add this when you are using same controller to redirect
var url = "YourActionName?parameterName=" + parameterValue;
window.location.href = url;
You can set up your element with
value="#model.productId"
and
onclick= addToWishList(this.value);
I am using this way, and worked perfectly:
//call controller funcntion from js
function insertDB(username,phone,email,code,filename) {
var formdata = new FormData(); //FormData object
//Iterating through each files selected in fileInput
formdata.append("username", username);
formdata.append("phone", phone);
formdata.append("email", email);
formdata.append("code", code);
formdata.append("filename", filename);
//Creating an XMLHttpRequest and sending
var xhr = new XMLHttpRequest();
xhr.open('POST', '/Home/InsertToDB');//controller/action
xhr.send(formdata);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
//if success
}
}
}
in Controller:
public void InsertToDB(string username, string phone, string email, string code, string filename)
{
//this.resumeRepository.Entity.Create(
// new Resume
// {
// }
// );
var resume_results = Request.Form.Keys;
resume_results.Add("");
}
you can find the keys (Request.Form.Keys), or use it directly from parameters.
You can easily make a <a> link in your view.
<a hidden asp-controller="Home" asp-action="Privacy" id="link"></a>
then in you javascript code use this:
location.href = document.getElementById('link').href;

Stop previous unobtrusive ajax call

I have a form like :
#using (Ajax.BeginForm("List", null, new AjaxOptions() { UpdateTargetId = "results" }, new { id = "myform" }))
{
<input id="search" type="text" value="" />
}
I declare javascript to send submit when user presses a key in my Search box :
<script type="text/javascript">
$("#search").on("keyup", function ()
{
$("#myform").submit();
});
</script>
But when users search quickly, browser start multiple ajax request, and wait the end of each call one by one.
How to stop the previous ajax call before sending another without removing ajax unobtrusive ?
I would suggest instead of directly calling $("#myform").submit();
Break it down to an $.ajax() request & abort if before making another one
$("#search").on("keyup", function (){
var xhr;
if (xhr){
xhr.abort(); //stop previous ajax
}
xhr = $.ajax({
type: "GET",
url: "#Url.Action(list)",
data : {formdata : $("#myform").serialize() },
success: function(response){
// do some stuffs with $("#results")
}
});
});

Redirect from partial view to view with json data object

I have a json data object which i need to pass from partial view to view with REDIRECT.
Lets say below is my partial view ( _createEmp.cshtml ):-
Note:- This partial view is in different view or page
<script type="text/javascript">
$(document).ready(function () {
LoadData();
});
function LoadData() {
$.ajax({
type: "GET",
url: baseURL + "Employee/GetEmpInfo",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
success: function (data) {
console.log(data);
**EmpData** = data; // EmpData object
},
error: function (error) {
console.log("Error: " + error);
}
});
}
</script>
<div>
<input type="submit" value="Save" onclick="SetEmpInfo()" />
</div>
And i want to transfer EmpData object to a different view (lets say NewEmp.cshtml), bind something in that view from passed "EmpData object" and open that view (or REDIRECT to view NewEmp.cshtml).
As you are using ajax, you could return the URL from your action and have it redirected in javascript.
Without seeing your controller action you would need to do something like this:
Controller
public ActionResult GetEmpInfo()
{
// Do stuff
return Json(new { success = true, redirecturl = Url.Action("GetEmpInfoSuccess") });
}
Then add something like this to your success handler in javascript:
Javascript (within your success handler)
success: function (data) {
if (data.success == true)
{
window.location = result.redirecturl;
}
}
Issuing a request to Employee/GetEmpInfo for getting the data and on success redirecting to other view - doesn't sound right
I think that you can do all this with one trip to server:
Write an Action that receives all the the parameters that GetEmpInfo receives. Lets call it NewEmployee.
If GetEmpInfo action is your code, reuse it's logic inside NewEmployee action to get EmpData. If it is not your code, you can use issue async request with HttpClient and get EmpData - All this performed on the server
Once you have EmpData you should have everything your need to return a NewEmp view.
In this particular case there is no need in AJAX at all. You can use regular form submit in case that you need to post some data or just a redirect to NewEmployee action.

Update Panel in ASP.NET MVC 3

I'm looking for a way to do a "Update Panel" in ASP.NET MVC 3. I found this link: How to make update panel in ASP.NET MVC but didn't work.
So, i did this in my view:
<div>
<input type="text" id="userName" />
<button type="button" onclick="searchUserByName()">Search</button>
</div>
<div id="usersPanel">
#{Html.RenderPartial("_UserList", Model);}
</div>
<script type="text/javascript">
function searchUserByName() {
var userName = $("#userName").val();
$.post('#Url.Action("SearchUserByName")',
{username: userName},
function (htmlPartialView) {
$("#usersPanel").html(htmlPartialView);
}
);
}
</script>
And in my controller:
public ActionResult SearchUserByName(string userName)
{
List<User> users = // code to search users by name
return PartialView("_UserList", users);
}
But i don't know if is a good (or right) way to do that, or if there is a way to do this with asp.net mvc 3. There is a better way to do this, or with asp.net mvc 3?
Just use ajax request to get the results from your action methods. It basically does the same thing as update panels in asp.net.
So something like the following.
$.ajax({
async: false,
cache: false,
type: 'POST',
url: /controller/action,
data: { id: idParam },
beforeSend: function (XMLHttpRequest) {
if (confirmMessage !== undefined) {
return confirm(confirmMessage);
}
return true;
},
success: function (data) {
// do stuff
},
error: function () {
alert('An error occured');
}
});
I would do it like that.
You might also want to take a look at client side libraries for handling bindings etc. Looks like knockoutjs will be included in MVC4
In View:
<script type="text/javascript">
var userName = $("#userName").val();
$.ajax({
url: "/<ControolerName>/SearchUserByName",
type: "POST",
data: { userName: userName},
success: function (result) {
$('#divResults').html(result);
},
error: function (ex) {
alert("Error");
}
<script>
<div id="divResults">
</div>
In controller:
public PartialViewResult SearchUserByName(string userName)
{
List<User> users = // code to search users by name
return PartialView("_users", users);
}

Passing parameters when submitting a form via jQuery in ASP.NET MVC

I'm trying to do a form submit to my controller through jQuery Ajax. The following code works for the most part, however, the ThreadId parameter does not get passed. If I call the controller directly without using jQuery, it gets passed, but when using jquery, I don't see the ThreadId after form.serialize(). WHat would be the easiest way to pass parameters (like ThreadId) to jQuery form post?
ASPX
<% Html.BeginForm("AddComment", "Home", new { ThreadId = Model.Id },
FormMethod.Post, new { #id = "AddComment" + Model.Id.ToString(),
#onsubmit = "javascript:AddComment(this);return false" }); %>
<%: Html.TextBox("CommentText", "", new { #class = "comment-textbox" })%>
<input id="Comment" type="submit" name="submitButton" value="Post Comment" />
<% Html.EndForm(); %>
JavaScript
AddComment = function (sender) {
var form = $(sender);
var data = form.serialize();
$.ajax({
type: "POST",
url: "/Home/AddComment",
data: data,
dataType: "html",
success: function (response) {
alert(response);
},
error: function (error) {
alert(error);
}
});
return false;
};
CONTROLLER
[HttpPost]
public ActionResult AddComment(string submitButton, Comment comment)
{
comment.CreatedDate = DateTime.Now;
comment.PosterId = LoggedInUser.Id;
_repository.AddComment(comment);
_repository.Save();
if (Request.IsAjaxRequest())
{
return View("Comment", comment);
}
else
return RedirectToAction("Index");
}
The ThreadId parameter is included in the action attribute of the form. When you are ajaxifying this form you are posting to /Home/AddComment and no longer supplying this parameter. You could do the following to ajaxify it:
$('#idofyourform').submit(function() {
$.ajax({
// use the method as defined in the <form method="POST" ...
type: this.method,
// use the action as defined in <form action="/Home/AddComment?ThreadId=123"
url: this.action,
data: $(this).serialize(),
dataType: 'html',
success: function (response) {
alert(response);
},
error: function (error) {
alert(error);
}
});
return false;
});
Another possibility is to include the ThreadId parameter inside the form as hidden field instead if putting it in the action attribute.

Categories