MVC [HttpPost/HttpGet] for Action

前端 未结 4 714
生来不讨喜
生来不讨喜 2020-11-27 16:08

I am using MVC C#.

Can somebody give an example on why one would use

[HttpPost/HttpGet] 

for an Action. How can an active have both

4条回答
  •  清酒与你
    2020-11-27 16:46

    You cant combine this to attributes.

    But you can put both on one action method but you can encapsulate your logic into a other method and call this method from both actions.

    The ActionName Attribute allows to have 2 ActionMethods with the same name.

    [HttpGet]
    public ActionResult MyMethod()
    {
        return MyMethodHandler();
    }
    
    [HttpPost]
    [ActionName("MyMethod")]
    public ActionResult MyMethodPost()
    {
        return MyMethodHandler();
    }
    
    private ActionResult MyMethodHandler()
    {
        // handle the get or post request
        return View("MyMethod");
    }
    

提交回复
热议问题