overload ActionResult - asp.net-mvc

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) {
}

Related

retrieve the ID parameter from url

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"];
}
}

MVC5 - How to know if an action input was completely empty

I have an action that takes a complex object as an input. I want to be able to populate any of the values with either POST data, or from the query string in a GET request. This works fine.
I also want to provide a default value if no user input was provided, however, this is not working because filter is never null, even if there were no querystring params from a GET request. What happens instead is, MVC just calls the model's default constructor without setting any properties instead of giving me a null.
public ActionResult Index(DataFilterInput filter = null)
{
if (filter == null)
filter = new DataFilterInput { Top = 100 };
var model = new IndexModel();
return View(model);
}
How can I know whether I should be defaulting the values in the absence of user input (I do not want to go into the Request query string or form collections)?
to provide a default value for your object this sample would work
public class SearchModel
{
public bool IsMarried{ get; set; }
public SearchModel()
{
IsMarried= true;
}
}
and if you want to validate the model
public ActionResult Index(DataFilterInput filter = null)
{
if (!ModelState.Isvalied)
filter = new DataFilterInput { Top = 100 };
var model = new IndexModel();
return View(model);
}
You can decare top nullable
public int? Top {get;set;}
So when no top value is provided it will be null by default and you can check it by using ==null or HasValue like this
public ActionResult Index(DataFilterInput filter )
{
if (!filter.Top.HasValue )
filter = new DataFilterInput { Top = 100 };
var model = new IndexModel();
return View(model);
}

MVC pass value from View (Jquery script) to 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

The model item passed into the dictionary is of type 'System.Data.Objects.ObjectQuery`1

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());
}

Value not passing when redirecting from controller to another controller while passing data in MVC 2

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

Resources