unwanted query string in RedirectToAction - asp.net-mvc

I am using redirect statement like below to go to specific action with parameter
return RedirectToAction(nameof(ActivityTypeController.Create), "ActivityType", new { selectedID = 34 });
and my action route configuration is
[Route("Create/{selectedID}")]
public IActionResult Create(int selectedID)
what I expected is
http://localhost:27945/ActivityType/Create/34
but it return
http://localhost:27945/ActivityType/Create?selectedID=34
I also use
RouteData.Values.Remove("selectedID")
but nothing changed!
I am using MVC6 with Asp.net 5 Template
Updated:
my redirected action is like below
[Route("Create/{selectedID}")]
public IActionResult Create(int selectedID)
{
BL.BO.ActivityTypeBO bo = new BL.BO.ActivityTypeBO();
ViewBag.Title = "title1";
ViewBag.Description = "some desc";
var data = bo.GetAll().Where(p => p.ParentID == null).OrderBy(p => p.Title);
SelectList parents;
parents = new SelectList(data, "ID", "Title", selectedID);
ViewBag.Parents = parents;
return View();
}
and I use RoutDate just before redirect to action
RouteData.Values.Remove("selectedID");
return RedirectToAction(nameof(ActivityTypeController.Create), "ActivityType", new { selectedID = 34 });

MVC will add the parameters like a query string.So, in cases like yours, you need to append it to the action param of RedirectToAction method.Below is the code
return RedirectToAction(nameof(ActivityTypeController.Create) + "/34" , "ActivityType");

Related

How to pass a list in a get request

I have an url that works for passing a List of strings
/Home/Index?Person%5B0%5D=Myname&Person%5B1%5D=Yourname
Unencoded it is
/Home/Index?Person[0]=Myname&Person[1]=Yourname
The Action Method is
public ActionResult(List<string> person)
{
...
}
The Parameter List person will be correctly filled with the values Myname and Yourname.
I need to redirect to this url using RedirectToAction
I would usually do
RedirectToAction("Index","Home",new {Parameter1=value1})
But obviously I cant use Person%5B0%5D as a parameter name, because it has ivalid characters.
How can I create such a link or should I use a different URL - scheme?
hi i worked on your query and finally got the result just check this code find weather it work with your query.
Controller code :
public ActionResult showString()
{
try
{
IEnumerable<string> persons = new[] { "myname", "urname" };
var values = new RouteValueDictionary(
persons
.Select((sampleper, index) => new {sampleper, index })
.ToDictionary(
key => string.Format("[{0}]", key.index),
value => (object)value.sampleper
)
);
return RedirectToAction("details", values);
}
catch (Exception)
{
throw;
}
}
and another action method is details with list as parameter
public ActionResult details(IEnumerable<string> persons)
{
ViewBag.person = persons;
return View();
}
it also works if you pass the link as
http://localhost:2266/Home/details?%5B0%5D=myname&%5B1%5D=urname
the view of details action method is
#{
ViewBag.Title = "details";
}
<h2>details</h2>
<ul>
#foreach (var i in ViewBag.person)
{
<li>#i</li>
}
</ul>

MVC4 Razor - Trying to get id in url for a blog post

All Im trying to do is get my url to have the blogid appending to it much like the following...
http://localhost/blog/blogpost/17
Here is my Controller...
public ActionResult BlogList(){ return View(_repository); }
public ActionResult BlogPost(string id)
{
ViewData["id"] = id;
if (ModelState.IsValid)
{
return RedirectToAction("BlogPost", new { id = id });
}
return View(_repository);
}
Now here is my route.config maproute
routes.MapRoute(
"MyBlog", // Route name
"blog/{action}/{id}", // URL with parameters
new { controller = "Blog", action = "blogpost", id =
UrlParameter.Optional } // Parameter defaults
);
Now I can get the url to appear when I click on a blog in the blogList. The page doesn't display the blog it displays a redirect loop message. If I omit the following code ...
if (ModelState.IsValid)
{
return RedirectToAction("BlogPost", new { id = id });
}
then I can display the blog. The url wont have the id value. Like this...
http://localhost/blog/blogpost/
What am I doing wrong?
The following code should work with your route:
// http://localhost/blog/bloglist
public ActionResult BlogList()
{
return View(_repository); // show all blog posts
}
// http://localhost/blog/blogpost/1
public ActionResult BlogPost(int? id = null)
{
if (id.HasValue == false || id.Value < 1)
{
// redirect to 404 page or BlogList
throw new NotImplementedException();
}
var blogPostObj = _repository.Find(id.Value);
if (blogPostObj == null)
{
// again redirect to 404
throw new NotImplementedException();
}
return View(blogPostObj);
}
Remove the BlogList() which takes 0 parameter
public ActionResult BlogList(){ return View(_repository); }
This is not required, since your id is type of string which can be null
The below code can be help you
public ActionResult BlogPost(string id)
{
var model=new ModelObject();
if(id!=null)
{
var model=Blogs.Find(id); //find it from repo
return View(model);
}
return View(model);
}
From your code it does not look like the id field is optional. Therefore I would change the route.
routes.MapRoute(
"MyBlog", // Route name
"blog/blogpost/{id}", // URL with parameters
new { controller = "Blog", action = "blogpost" },
new { id = #"(\d)+"} //ensures value is numeric.
);
RouteData.Values["id"] + Request.Url.Query

parameter problem in asp.net mvc

I'm new to asp.net mvc. I have index method with parameter id :
public ActionResult Index(int id)
{
var dc = new ServicesDataContext();
var query = (from m in dc.Mapings
where m.CustomerID == id
select m);
// var a = dc.Customers.First(m => m.CustomerId == id);
// ViewData.Model = a;
// return View();
return View(query);
}
Now when I try to redirect to index from edit i get an error " The parameters dictionary contains a null entry for parameter 'id' of non-nullable type 'System.Int32' for method 'System.Web.Mvc.ActionResult Index(Int32)' in 'MVCServices.Controllers.CustomerserviceController'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter.
[HttpPost]
public ActionResult Edit( FormCollection form)
{
var id = Int32.Parse(form["CustomerServiceMappingID"]);
var datacontext = new ServicesDataContext();
var serviceToUpdate = datacontext.Mapings.First(m => m.CustomerServiceMappingID == id);
TryUpdateModel(serviceToUpdate, new string[] { "CustomerID", "ServiceID", "Status" }, form.ToValueProvider());
if (ModelState.IsValid)
{
try
{
var qw = (from m in datacontext.Mapings
where id == m.CustomerServiceMappingID
select m.CustomerID).First();
datacontext.SubmitChanges();
//return Redirect("/Customerservice/Index/qw");
return RedirectToAction("Index", new { qw = qw });
}
catch{
}
}
return View(serviceToUpdate);
}
This is the View:
#Html.ActionLink("Back to List", "Index")
The id in the Index method turns out to be the customerid fetched from another controller while id in Edit is from another table.Can you please let me know the mistake I've been doing and how to solve it?
Do this in the Edit action:
return RedirectToAction("Index", new { id = qw });

Rewriting the URL for a Controllers Action Method

I have a controller called Person and it has a post method called NameSearch.
This method returns RedirectToAction("Index"), or View("SearchResults"), or View("Details").
The url i get for all 3 possibilities are http://mysite.com/Person/NameSearch.
How would i change this to rewrite the urls to http://mysite.com/Person/Index for RedirectToAction("Index"), http://mysite.com/Person/SearchResults for View("SearchResults"), and http://mysite.com/Person/Details for View("Details").
Thanks in advance
I'm assuming your NameSearch function evaluates the result of a query and returns these results based on:
Is the query valid? If not, return to index.
Is there 0 or >1 persons in the result, if so send to Search Results
If there is exactly 1 person in the result, send to Details.
So, more of less your controller would look like:
public class PersonController
{
public ActionResult NameSearch(string name)
{
// Manage query?
if (string.IsNullOrEmpty(name))
return RedirectToAction("Index");
var result = GetResult(name);
var person = result.SingleOrDefault();
if (person == null)
return RedirectToAction("SearchResults", new { name });
return RedirectToAction("Details", new { id = person.Id });
}
public ActionResult SearchResults(string name)
{
var model = // Create model...
return View(model);
}
public ActionResult Details(int id)
{
var model= // Create model...
return View(model);
}
}
So, you would probably need to define routes such that:
routes.MapRoute(
"SearchResults",
"Person/SearchResults/{name}",
new { controller = "Person", action = "SearchResults" });
routes.MapRoute(
"Details",
"Person/Details/{id}",
new { controller = "Person", action = "Details" });
The Index action result will be handled by the default {controller}/{action}/{id} route.
That push you in the right direction?

ASP.NET MVC: Server Validation & Keeping URL paramters when returning the view

I currently have the following code for the POST to edit a customer note.
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult EditNote(Note note)
{
if (ValidateNote(note))
{
_customerRepository.Save(note);
return RedirectToAction("Notes", "Customers", new { id = note.CustomerID.ToString() });
}
else
{
var _customer = _customerRepository.GetCustomer(new Customer() { CustomerID = Convert.ToInt32(note.CustomerID) });
var _notePriorities = _customerRepository.GetNotePriorities(new Paging(), new NotePriority() { NotePriorityActive = true });
IEnumerable<SelectListItem> _selectNotePriorities = from c in _notePriorities
select new SelectListItem
{
Text = c.NotePriorityName,
Value = c.NotePriorityID.ToString()
};
var viewState = new GenericViewState
{
Customer = _customer,
SelectNotePriorities = _selectNotePriorities
};
return View(viewState);
}
}
If Validation fails, I want it to render the EditNote view again but preserve the url parameters (NoteID and CustomerID) for something like this: "http://localhost:63137/Customers/EditNote/?NoteID=7&CustomerID=28"
Any ideas on how to accomplish this?
Thanks!
This action is hit by using a post. Wouldn't you want the params to come through as part of the form rather than in the url?
If you do want it, I suppose you could do a RedirectToAction to the edit GET action which contains the noteId and customerId. This would effectively make your action look like this:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult EditNote(Note note)
{
if (ValidateNote(note))
{
_customerRepository.Save(note);
return RedirectToAction("Notes", "Customers", new { id = note.CustomerID.ToString() });
}
//It's failed, so do a redirect to action. The EditNote action here would point to the original edit note url.
return RedirectToAction("EditNote", "Customers", new { id = note.CustomerID.ToString() });
}
The benefit of this is that you've removed the need to duplicate your code that gets the customer, notes and wotnot. The downside (although I can't see where it does it here) is that you're not returning validation failures.

Resources