How to pass a list in a get request - asp.net-mvc

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>

Related

unwanted query string in RedirectToAction

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");

Reference DropDownList selected value from enclosing Form

I'm just getting started with MVC5 (from WebForms), and dropdownlist bindings are giving me some fits.
I'd like to get this working using a GET request back to the page, with a selected value parameter. I'm hopeful that I can specify the route arguments in the form itself, so I'd like to reference the DDL's SelectedValue.
<p>
#using (Html.BeginForm("Index", "Profile", FormMethod.Get, new { id = WHATDOIPUTHERE} )) {
#Html.AntiForgeryToken()
#Html.DropDownList("ApplicationID", new SelectList(ViewBag.ApplicationList, "ApplicationID", "ApplicationName", ViewBag.SelectedApplicationId), new {onchange = "this.form.submit();"})
}
</p>
I can make it work with a POST form, but that requires a second controller method so I end up with
public ActionResult Index(long? id) {
ConfigManager config = new ConfigManager();
//handle application. default to the first application returned if none is supplied.
ViewBag.ApplicationList = config.GetApplications().ToList();
if (id != null) {
ViewBag.SelectedApplicationId = (long)id;
}
else {
ViewBag.SelectedApplicationId = ViewBag.ApplicationList[0].ApplicationID; //just a safe default, if no param provided.
}
//handle profile list.
List<ProfileViewModel> ps = new List<ProfileViewModel>();
ps = (from p in config.GetProfilesByApp((long)ViewBag.SelectedApplicationId) select new ProfileViewModel(p)).ToList();
return View(ps);
}
//POST: Profile
//read the form post result, and recall Index, passing in the ID.
[HttpPost]
public ActionResult index(FormCollection collection) {
return RedirectToAction("Index", "Profile", new {id = collection["ApplicationId"]});
}
It would be really nice to get rid of the POST method, since this View only ever lists child entities.
What do you think?
You can update your GET action method parameter name to be same as your dropdown name.
I also made some small changes to avoid possible null reference exceptions.
public ActionResult Index(long? ApplicationID) {
var config = new ConfigManager();
var applicationList = config.GetApplications().ToList();
ViewBag.ApplicationList = applicationList ;
if (ApplicationID!= null) {
ViewBag.SelectedApplicationId = ApplicationID.Value;
}
else
{
if(applicationList.Any())
{
ViewBag.SelectedApplicationId = applicationList[0].ApplicationID;
}
}
var ps = new List<ProfileViewModel>();
ps = (from p in config.GetProfilesByApp((long)ViewBag.SelectedApplicationId)
select new ProfileViewModel(p)).ToList();
return View(ps);
}

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

from data to controller and passing it to form

I'm doing my first steps in mvc and I need help.
I'm passing data from view to this controller and I need to pass the selected items with there details to a different view (that is a form that the user add his email details) and I cant figure out how to .
This is how I'm getting the details to the controller from the submitted form
public ActionResult list()
{
var AllItems = db.menu.ToList();
Mapper.CreateMap<Menu, SelectableMenu>();
return View(AllItems.Select(m => new SelectableMenu { price = m.price, MenuId = m.MenuId, Name = m.Name })
.ToList());
}
[HttpPost]
public ActionResult List(IEnumerable<SelectableMenu> item)
{
var userSelectedMenu = item.Where(m => m.IsSelected).Select(m => m.Name + m.price + m.MenuId);
if (userSelectedMenu != null && userSelectedMenu.Any())
{
return View("bla");
}
return View();
}
Use method ReditectToActionstring actionName, string controllerName, Object routeValues)
for details go to: http://msdn.microsoft.com/en-us/library/dd460311(v=vs.108).aspx
You can return different view using return View("ViewName",model)
For eg:
[HttpPost]
public ActionResult List(IEnumerable<SelectableMenu> item)
{
var userSelectedMenu = item.Where(m => m.IsSelected).Select(m => m.Name + m.price + m.MenuId);
if (userSelectedMenu != null && userSelectedMenu.Any())
{
return View("YourDiffrentViewName",userSelectedMenu); // This will pass your model to your Different view
}
return View();
}
Then in your new view you will have to strongly typed it with your model.
For eg :
Your view will be as follows:
#model ProjectName.models.YourClassName //Your class/model namespace
#using(Html.BeginForm())
{
#Html.TextBoxFor(m => Model.Property) //This will create textbox for your property
<input type="submit" value="Submit" />
}
For more on stronly typed views visit:
http://www.c-sharpcorner.com/UploadFile/abhikumarvatsa/strongly-typed-views-in-mvc/
http://www.howmvcworks.net/OnViews/BuildingAStronglyTypedView
You will need twosteps for this
Step 1
Make a model(it is more effective) use it in a view to pass your data to controller through post in submission of form.
Step 2
Receive the data into the controller method then use
return View("yourNewpage","yourdatamodelobject"); in the controller action to pass the data in the action result view of another page.
Alternatively, if the view is in another controller
then you can receive data here in the post action method and use Return RedirectToAction("ActionName", "ControllerName", "DataModelObject") to pass to a diffrent controller

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?

Resources