How to call Action on Button click from JQuery - c#

With ASP.NET MVC, I want to call action of controller on Button Click from JQuery.
Controller:
public class HomeController : Controller
{
//
// GET: /Home/
public ActionResult Index()
{
return View();
}
public ActionResult PersonInfo(string name, string city)
{
// other code for assign ViewData
return View();
}
}
I have two textBox and one Button in Index.chtml page. I want to display Url like 'http://localhost:2526/PersonName'. for city I want optional perameter and don't want in Url. so, I mapped route as below:
routes.MapRoute(
"Default", // Route name
"",
new { controller = "Home", action = "Index" } // Parameter defaults
);
routes.MapRoute(
"PersonInfo", // Route name
"{name}", // URL with parameters
new { controller = "Home", action = "PersonInfo", name= "" , city = ""} // Parameter defaults
From browser if I enter Url like 'http://localhot:2526/John' then PersonInfo view displayed successfully.
I visited link related my question. But I also want to pass parameters.
Anyone help me How can I call action on button click from JQuery.

you can pass parameters as query string for example:
$('#buttonId').click(function(){
document.location =
'#Url.Action("MyAction","MyController")'+'?'+'parameterToSend = #value';
});
your link will be like
MyController/MyAction?parameterToSend=value

You want to add the paramaters inside the Url.Action Method to avoid the / at the end of your host.
#Url.Action("PersonInfo","Home" , new {name=Model.Name, city=Model.City })
//I believe this will look at your routes and generate localhost:2526/John/JohnsCity
Are your paramaters part of your model? If so the above will work. If not than you can use 1AmirJalali answer but replace the / before appending the paramaters since if they paramaters are not part of your model then they are probably coming via javascript variables.

Related

Asp.net get submit method not working when url is mapped

I have a asp.net mvc form and i want to submit it to same page via get method, it's used for search purpose.
The url is mapped with route key value id.
#using (#Html.BeginForm("Contact", "Home",FormMethod.Get))
{
#Html.TextBox("id", null,
new
{
type = "time"
}
);
<input type="submit" />
}
When the form is generated the action attribute is containing the key value like /Home/Contact/myname.
Here myname is value of id present in url.
When form is submitted value key value for id is getting appended to URL like
http://localhost:57247/Home/Contact/myname?id=11%3A11
The action method is reading myname value instead of 11%3A11.
Action Method:
public ActionResult Contact(string id)
{
ViewBag.Message = id;
return View();
}
It's working fine with post method.
How to fix this?
replace #Html.BeginForm("Contact", "Home",FormMethod.Get)
with #Html.BeginForm()
By default forms are sent to same url they are rendered on and default method is get.
#Html.BeginForm() by default produces a METHOD="POST"
As for your parameter you might want to name it differently.
Default Mvc route is configured like this
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
Depending on mvc version it can be in global.asax or App_Start\routeconfig.cs
So your "MyName" in url perfectly matches default id parameter and it has higher priority than query string parameters.
If you name your parameter differently (not id).
Change it to "q" for example in action and in view.
Your URLs will change to /Home/Contact?q=myname and everything should start working as expected.
Now you say that you want a solution with url mapping.
So you have to figure out for yourself what url scheme you want.
If you have a form and want it to post to /home/contact/myname?id=notyourname, than you have a conflict which to solve you will have to somehow change binding priorities in mvc.
Now you can inspect querystring on your own in your action and figure out new id passed without binding. After that you can return RedirectToAction("Contact", new{id = figuredId}) and the url in browser will be what you want it to be.
You can change the query parameter name and have your action recieve 2 parameters
public ActionResult Contact(string id, string q){
if (!string.IsNullOrWhitespace(q)){
return RedirectToAction("Contact",new{id=q});
}
}
To send request to /Home/Contact you should use #Html.BeginForm("Contact","Home",new{id=null}, FormMethod.Get)

How to use RouteConfig to append a page URL

I am struggling to get my code work, but I think I've read enough to suggest this is the correct way to approach this.
On my intranet, I'd like the user to type in a single word to search into a textbox, and check a checkbox. When the new page loads, I'd like the URL rewritting services of ASP.NET MVC to kick in and change a value from
mysite.com/?id=blah&isChecked=true
to
mysite.com/home/index/blah/true
My code isn't working in the sense of it gives no error, but doesn't do what I am explaining. So, I've removed the check box to just focus on the textbox.
My only route is
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{MyType}",
defaults: new { controller = "Home", action = "Index", MyType = UrlParameter.Optional }
);
My Controller
public ActionResult Index()
{
ViewBag.Message = "Modify this";
return View();
}
[HttpGet]
public ActionResult Index(string MyType)
{
ViewBag.Message = "..." + MyType;
return View();
}
and my View has
#using (Html.BeginForm("Index", "Home",FormMethod.Get))
{
<input name="MyType" /><br />
<input type="submit" />
}
#Html.ActionLink("Click me", "Index", new { #MyType = "Blah" }) //renders correctly
The problem is, it shows the querystring still in the address bar
mysite.com/?MyType=MySearchValue
instead of
mysite.com/Home/Index/MySearchValue
You can't do this purely with routing because the browser will always send form values as query string parameters when they are part of a GET request. Once the request has been sent to the server, the MVC framework can't do anything about the URL that was used.
This leaves you with only one real option (assuming you don't want to send a custom request using JavaScript), which is to explicitly redirect to the desired URL (meaning you will always have two requests when this form is submitted).
The simplest way of doing this is simply in the controller (rather, in a separate controller to ensure that there is no conflict in method signatures):
public class FormController : Controller
{
public ActionResult Index(string MyType)
{
return RedirectToAction("Index", "MyProperController", new { MyType });
}
}
If you direct your form to this controller action, MVC will then use the routing engine to generate the proper URL for the real action and redirect the browser accordingly.
You could do this from the same controller action but it would involve inspecting the request URL to check whether a query string was used or not and redirecting back to the same action, which is a little odd.

Redirect to more specific URL via routing

I am using the following routing in my project
routes.MapRoute(
"ProductRoute", // Route name
"product/{id}/{title}", // URL with parameters
new { controller = "product", action = "Index", id = UrlParameter.Optional }, // Parameters defaults
new[] { "PriceCompare.Controllers" }
);
The problem at hand is how the url is displayed in return. One can access the URL in any of the following ways:
http://mywebsite.com/product/22/full-title
http://mywebsite.com/product/22/half
http://mywebsite.com/product/22/
All is fine, as all these URLs redirect to the desired place. But, what i think would be nice is even if someone uses the 2nd or 3rd approach, the return URL in browser should show the 1st URI.
Just like StackOverflow. For example if you visit the following URL
stackoverflow.com/questions/734249/, your browser address will show the complete URL in browser stackoverflow.com/questions/734249/asp-net-mvc-url-routing-with-multiple-route-values
How can this be achieved?
You can either implement your own Route or do something like this in your action:
public ActionResult Index(int? id, string title = null)
{
if (String.IsNullOrWhiteSpace(title))
{
var product = // load product
return Redirect(Url.Action("Index", "Product",
new { id = id, title = product.Title }));
}
// your code
}

MVC4 and Routing

I have a single controller and view working that calls a web service, and returns a result. At the moment, it's my default controller, called Home, and it uses the Index view page.
It's working. I can post data and then put something on the refreshed screen. It reloads the same view.
Now, once I submit, and I get a good reply, I want to load a different controller/view.
My routes look like this right now:
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Home",
"{lang}",
new { controller = "Home", action = "Index", lang="English" });
routes.MapRoute(
"Location",
"{lang}",
new { controller = "Location", action = "Index", lang = "English" });
I created a controlled called Location, and it just has this:
//LocationController
public class LocationController : Controller
{
public ActionResult Index()
{
return View();
}
}
In my home controller, I am doing the logic, and then attempting to load the new page.
[HttpPost]
public ActionResult Index(HomeModel model)
{
var proxy = new Proxy();
var r = proxy.GetLocationByAddress(model.SearchString, o.ToString());
if(r==null)
{
ViewBag.Error = "Error during search";
return View(model);
}
ViewBag.Error = string.Format("Found {0} at {1}, {2}", r.StreetName, r.Latitude, r.Longitude);
return RedirectToAction("Index", "Location");
}
But when I run it, submit it, step through, it hits the RedirectToAction - but ... the Home screen simply refreshes. I never see the new Location view. What am I doing wrong here? I have't grasped Routes yet... I need to pass a new object to the Location.Index screen to display...
Your route mapping is incorrect, check this out: http://www.asp.net/mvc/tutorials/controllers-and-routing/creating-custom-routes-cs
routes.MapRoute(
"Location",
"Location/{lang}",
new { controller = "Location", action = "Index", lang = "English" });
I don't think so you need to make any changes. As in your case you want to load different controller with its respecting view you need below change only
replace this code return RedirectToAction("Index", "Location");
with this code return Redirect("http://www.yoursite.com/Location/Index");
Your change is like redirection from one page to another therefore you need to put your complete path here
please try & reply if any problem

Using a query string with an form in MVC3

I have an MVC3 view with a form and i want to pass in a parameter via query string. Heres my form
#using (Html.BeginForm("LogOn", "Account", new { db = #Request.QueryString["db"] }, FormMethod.Post))
Heres my Controller
[HttpPost]
public ActionResult LogOn(LogOnModel model,string db)
When I click my Login button, and step through the code, the param db is null. Im passing it in like this:
http://localhost:64632/?db=someValue
My route looks like this:
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{db}", // URL with parameters
new { controller = "Account", action = "LogOn", db = UrlParameter.Optional } // Parameter defaults
);
What am i doing wrong?
Your route is expecting db to be a token in the url:
http://localhost:64632/Account/LogOn/someValue
You could grab the value from the querystring in your controller and store the db parameter in a ViewBag and it will be available on your form.
If that's the only route you have, then presumably the page you're currently on looks like "/controller/action/dbValue". In this case,
#Request.QueryString["db"]
won't fetch anything because db is a route value, it's not part of the query string. You could use
#ViewContext.RouteData.Values["db"]
instead.
It works. I am doing the same thing. I can retrieve the query string values on a http post: Request["queryparametername"]
well, this is a get method link : "http://localhost:64632/?db=someValue"
and you used the HttpPost attribute.

Categories