3

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!

2 Answers 2

2

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
    }
}
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.