Ok, I have 2 models that inherit from one abstract class:
public abstract class Search
{
[Required]
public string Name{get;set;}
}
public class PageModelA : Search
{}
public class PageModelB : Search
{}
The search page is a partial view.
How can I pass either of these models to one action method:
[HttpPost]
public ActionResult Search(??? search)
{}
Thanks!
You could create a view model that contains both objects. Then pass only the appropriate model and checking for null
on the controller.
class SearchModel
{
public PageModelA { get; set; }
public PageModelB { get; set; }
}
[HttpPost]
public ActionResult Search(SearchModel search)
{
if (SearchModel.PageModelA != null)
{
//Do something with PageModelA
}
else
{
//Do something with PageModelB
}
}
The other option here is to check the type
[HttpPost]
public ActionResult Search(Search search)
{
if ((search) is PageModelA )
{
//Do something with PageModelA
}
else if ((search) is PageModelB )
{
//Do something with PageModelB
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.