Redirect to div in page with # - c#

I want to redirect to a certain div of a webpage after handling some data in a controller. Is their any way to add the '#' to the end of the url? Or should I handle it with javascript?
Example:
[HttpPost]
public async Task<IActionResult> Edit(ViewModel model){
....
return RedirectToAction("Info", new { id = model.Id, "#" = "item_55" });
}
=> Should redirect to /Info/id=4#item_55

RedirectToAction has an overload that allows you to specify the fragment. Here's an example:
return RedirectToAction("Info", "Controller", new { id = model.Id }, "item_55");
Note that you also need to specify the controller as one of the arguments, as I've done above.

Related

Save querystring Bewteen Actions

I have an index action that can be filtered and is done so by using a query string. When I choose a record I move to the Details action. From there I can navigate to other actions related to this record which will then lead me back to the Details action. I would like to be able to save the URL from the Index page which will have the query string parameters intact. Obviously I can't do this with a straight Request.UrlReferrer since it won't be correct if the previous action wasn't Index. I have come up with a solution but I was wondering if there was a better way. Thanks!
public ActionResult Details(int? id)
{
var url = Request.UrlReferrer;
// Save URL if coming from the Employees/Index page
if (url != null && url.AbsolutePath == "/Employees")
Session.Add("OfficeURL", url.ToString());
// Model Stuff
return View();
}
Details View
#Html.ActionLink("Back to List", "Index", null, new { #href = Session["OfficeURL"] })
You need to pass a "return URL" with your links to the other views. Essentially:
Index.cshtml
#Html.ActionLink("View Details", "Details", "Foo", new { returnUrl = Request.RawUrl })
This will have the effect of putting the current index URL in the query string of the link. Then, in your other actions, you'll accept this as a param and store it in ViewBag:
public ActionResult Details(int? id, string returnUrl = null)
{
...
ViewBag.ReturnUrl = returnUrl;
return View();
}
Then, in these other views, you'll utilize this ViewBag member in the same way as above:
Details.cshtml
#Html.ActionLink("Click Me!", "Foo", "Foo", new { returnUrl = ViewBag.ReturnUrl })
When you're ready to go back to the index, then, you'd link/redirect to this return URL that you've been passing around.

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
}

ASP MVC and changing url of posted form

I have an MVC 4 app and I am using a RESTful methodology for my URLs. I have the following routes registered in my app (along with others that are not relevant to my question:
//EDIT
routes.MapRoute(alias + "_EDIT", alias + "/{id}/edit",
new { controller = controllerName, action = "edit" },
new { httpMethod = new RestfulHttpMethodConstraint(HttpVerbs.Get) });
//PUT (update)
routes.MapRoute(alias + "_PUT", alias + "/{id}",
new { controller = controllerName, action = "update" },
new { httpMethod = new RestfulHttpMethodConstraint(HttpVerbs.Put) });
I have the following methos in my controller mapping to these routes:
public override ActionResult Edit(int id)
{...}
public override ActionResult Update(RequestEditViewModel userModel)
{
if (!ModelState.IsValid)
{
//do some stuff to ensure lookups are populated
...
return View("Edit", userModel);
}
}
In my app when I perform a request to edit a request my URL looks like:
http://server/request/1/edit
it correctly calls the Edit method on my controller.
My Edit.cshtml uses the followng to ensure the Update method is called on PUT:
#using (Html.BeginForm("Update", "Request"))
{
#Html.HttpMethodOverride(HttpVerbs.Put);
...
}
My form is generated as follows:
<form action="/requests/71" method="post" autocomplete="off" novalidate="novalidate">
<input name="X-HTTP-Method-Override" type="hidden" value="PUT"/>
...
</form>
When I click the submit button it correctly calls my Update method.
OK...Now for the issue. If my model is NOT valid I want to return back the Edit model. As you can see in the above code but, the URL is the one called from the submit button:
http://server/request/1
not
http://server/requests/1/edit
I have tried an reviewed two other options but both of these redirect the request back through the Edit method again which adds additional overhead and also puts all the model values in the querystring which I do NOT want:
return RedirectToAction("Edit", userModel);
return RedirectToRoute("requests_Edit", userModel);
So, is there a way to just return the View as I have in my code but, ensure the URL changes back and include the "/edit"?
The only alternative I have come up with is to perform an AJAX call and put the update that way the URL never changes, but I was trying to avoid that for this form.
Conceptually, you want to be doing something like a Server.Transfer (that is, making on URL appear to be another.) This discussion may be of use to you:
How to simulate Server.Transfer in ASP.NET MVC?

How to call Action on Button click from JQuery

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.

How to save query values when searching? ASP.NET MVC

I have such an action method:
[AcceptVerbs(HttpVerbs.Get)]
public ActionResult Search(String filter, String value, Int32? page) {
var set = new List<Employee>();
switch(filter) {
case "by-name": {
set = this.repository.Get(
e => (e.LastName + " " + e.FirstName + " " + e.MiddleName) == value
).ToList();
break;
}
case "by-empn": {
set = this.repository.Get(
e => e.EmployeeNumber == value
).ToList();
break;
}
default: return RedirectToAction("Search", "Employee");
}
ViewBag.SearchedEmployees = set.Count();
return View(set.ToPagedList(page ?? 1, PageSize));
}
Search view is like this:
#if(Model.Count > 0) {
foreach(var item in Model) {
Html.RenderPartial("Employee.Card", item);
}
#Html.PagedListPager(
Model,
page => Url.Action("Search", new { page = page }),
new PagedListRenderOptions {
LinkToFirstPageFormat = "<< Beginning",
LinkToPreviousPageFormat = "< Back",
LinkToNextPageFormat = "Forth >",
LinkToLastPageFormat = "End >>"
}
)
}
Search form is presented as a partial view:
#using(Html.BeginForm("Search", "Employee", FormMethod.Get, new { #class = "search-form" }))
{
<p>
#Html.TextBox("value")
</p>
<p>
#Html.RadioButton("filter", "by-name", true) By name <br/>
#Html.RadioButton("filter", "by-empn") By empn <br/>
</p>
<p>
<input type="image" src="#Url.Content("~/Content/Images/Search.png")" />
</p>
}
Problem: I have N page links. When I try to go to the second page I face an infinite loop of redirects. That's the way I implemented my action - default case is fired. So filter/value values are null on the second action call? Why?
How do I refactor my search action?
Also how should I configure route for such an action?
Thanks!
EDIT
So should route for the search action look like:
routes.MapRoute(
null,
"{controller}/{action}/Page{page}/filter{filter}/val{value}",
new { controller = "Employee", action = "Search" }
);
?
EDIT 2
So it is possible to write next:
page => Url.Action("Search", new { filter = ViewBag.SearchFilter, value = ViewBag.SearchValue, page = page }),
And inside a controller:
public ActionResult Search(String filter, String value, Int32? page) {
ViewBag.SearchFilter = filter;
ViewBag.SearchValue = value;
// ...
}
Is this right?
So filter/value values are null on the second action call? Why?
Because their corresponding input fields are inside a separate form and are never sent to the server.
You seem to be using some custom Html.PagedListPager helper (the code for which you haven't shown) but I guess that this helper generates the page links as anchors and it simply doesn't take into account any current query string or POSTed values when generating those links. So the href of your pagination link looks like this /SomeController/Search?page=5 instead of the correct one which would take into account those parameters which is /SomeController/Search?page=5&filter=somefilter&value=somevalue.
You can now easily understand why the filter and value parameters in your controller action are always null. It's because you never send them to the server when clicking on the pagination links.
So in order to resolve this issue you could modify this custom HTML helper that you are using to generate the pagination links to include those additional parameters. Or maybe the helper allows you to pass additional parameters? Check the documentation if this is some third party plugin that you are using.

Categories