In MVC I am trying to pass an optional ID parameter from one ActionResult method and I want to capture that ID in another ActionResult method. I currently have the following code but I still can't find a way to get the ID in the Method2().
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Method1(SomeModel model)
{
int someID = model.something.Id;
.
..
...
return RedirectToAction("Method2", new { userID = someID});
}
After clicking on a button on Method1's View page, the code will direct me to Method2 page and I will see something like this in my URL
http://localhost:1234/myController/method2?userid=100 note that the ?userid=100 was sucessfully passed to the URL when Method2 got called.
and this is my Method2. I am trying to get the userid but I can't.
[HttpGet]
public ActionResult Method2()
{
**I want to get the userID from the URL**
}
I even tried to use int? id but still I am getting a null for id.
public ActionResult Method2(int? id)
{
//id return null all the time
}
Any help on how I can get the userid in the URL in Method2()?
your query string's variable name and actionresult variable name must match
[HttpGet]
public ActionResult Method2(int userid)
{
//your code
}
or even
public ActionResult Method2(int? userid)
{
//id return null all the time
}
The value key value pair for userid is in the request querystring collection. To get it do something like the following:
if (Request.QueryString.Count > 0)
{
if(Request.QueryString["userid"] != null)
{
int userId = (int)Request.QueryString["userid"];
}
}
Related
I want to route a URL like http://localhost:8888/api/orders?id=1
to an action, but it only works when the URL is given in this format: http://localhost:8888/api/orders/1
Two actions:
[HttpGet]
public IActionResult Get(bool includeItems=true)
{
var results = _repository.GetAllOrders(includeItems);
return Ok(_mapper.Map<IEnumerable<Order>, IEnumerable<OrderViewModel>>(results));
}
[HttpGet("{id:int}")]
public IActionResult Get(int id)
{
var order = _repository.GetOrderById(id);
if (order != null)
return Ok(_mapper.Map<Order, OrderViewModel>(order));
else
return NotFound();
}
It works fine if I send a URL like:
http://localhost:8888/api/orders?includeItems=false.
When I send the URL http://localhost:8888/api/orders?id=1, it gets mapped to the first Action which has includeItems as parameter.
I have [Route("api/[Controller]")] attribute on top of my controller.
I want to pass a value from the view to the controller the value is retrieve via jquery when I use the code below it does not work the value is null in the controller.
//Hardcoded to test
var groupId = 1;
$('#timeList').load('/Time/Index/' + groupId);
public ActionResult Index(int? groupId)
{
AddProjectToViewData(-1);
return View(_service.ListTimes());
}
Try this:
var groupId = 1;
$('#timeList').load('/Time/Index', {groupId: groupId}); //Send named parameter
[HttpGet]
public ActionResult Index(int? groupId)
{
AddProjectToViewData(-1);
return View(_service.ListTimes());
}
Hope this helps
assuming that you are using default routes in global.asax.cs you can retrieve this value in id
public ActionResult index(int? id)
{
AddProjectToViewData(-1);
return View(_service.ListTimes());
}
if you do wish to receive it in groupid you have to change jquery code a little
//Hardcoded to test
var groupId = 1;
$('#timeList').load('/Time/Index?groupid=' + groupId);
You want to do either a post or a get, and I think you may want to pass back a string or json. For ease, I'll show you a get with json:
///your javascript
var groupId =1;
$.get('Time/Index/' + groupId, function(data) {
$('#timeList').val(data);
///might need to do a for each since you are returning a list or whatever
});
///your controller logic
[HttpGet]
public string Index(int? groupId)
{
AddProjectToViewData(-1);
//might want to pass back json here
return WhateverYourDataIs.ToString();
}
Hope this helps
im trying to get the controller in my mvc application to edit a specific entity from a data model once the user clicks on the edit button, however I can't seem to make it work. I keep getting this error
The model item passed into the dictionary is of type 'System.Data.Objects.ObjectQuery`1[MvcApplication1.Models.New]' but this dictionary requires a model item of type 'MvcApplication1.Models.New'.
what am I doin wrong. is it due to the strongly typed view??
here is my controller:
public ActionResult Edit(int id)
{
var productToEdit = from s in _entities.NewSet // return the story matching the clicked id
where s.storyId == id
select s;
return View(productToEdit);
}
// POST : Edit
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Edit(New productToEdit)
{
try
{
var originalNews = (from s in _entities.NewSet
where s.storyId == productToEdit.storyId
select s).FirstOrDefault();
_entities.ApplyPropertyChanges(originalNews.EntityKey.EntitySetName, productToEdit);
_entities.SaveChanges();
return RedirectToAction("Index");
}
catch
{
return View();
}
}
can someone give me a few pointers please. Im still new to all of this.
Change your Edit action with Int Parameter to as follows:
public ActionResult Edit(int id)
{
var productToEdit = from s in _entities.NewSet
where s.storyId == id
select s;
return View(productToEdit.FirstOrDefault());
}
Is it possible to pass data from one controller to another? When my second controller is called the int id is showing the WRONG value:
I have one controller:
public ActionResult Index(int id)
{
return RedirectToAction("New", "NewProducts", id);
}
NewProductsController:
public string New(int id)// <--------id never has correct number when called
{
return "value: " + id;
}
You need to use either a RouteValueDictionary or an anonymous type with an id property for the route values otherwise it will use the properties on the Int32 object id to fill the route values dictionary.
public ActionResult Index(int id)
{
return RedirectToAction("New", "NewProducts", new { id = id } );
}
Hope it will work
public ActionResult Index(int id)
{
return RedirectToAction("New?id=" + id, "NewProducts");
}
this is my action "Index"
when i first go to page i dont have the "pageParent"
so i dont get the page.
just if i enter to it like this "http://localhost:50918/Page?pageParent=1" it's enter.
how to make "http://localhost:50918/Page" to work?
public ActionResult Index(int pageParent)
{
var id = pageParent;
var pages = (from p in db.pages
where p.pageParent == id
select p);
PageParentModel model = new PageParentModel();
model.page = pages;
model.pageParent = id;
return View(model);
}
Modify your Action like this
public ActionResult Index(int? pageParent) {
// this way your pageParent parameter is marked to be nullable
// dont forget to check for the null value in code
}
You can set a default value for use too in the case that the parameter isn't supplied in the querystring - e.g.:
public ActionResult Index([DefaultValue(1)] int pageParent) {
}