开发者

C# MVC 2 Pass multiple object types to one controller action

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.

开发者_Go百科

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜