ASP.Net MVC 4 Form with 2 submit buttons/actions

前端 未结 7 1547
故里飘歌
故里飘歌 2020-11-28 21:45

I have a form in ASP.Net and razor.

I need to have two ways of submitting said form: one that goes through the Edit action, and another that goes throug

7条回答
  •  孤城傲影
    2020-11-28 22:18

    That's what we have in our applications:
    Attribute

    public class HttpParamActionAttribute : ActionNameSelectorAttribute
    {
        public override bool IsValidName(ControllerContext controllerContext, string actionName, MethodInfo methodInfo)
        {
            if (actionName.Equals(methodInfo.Name, StringComparison.InvariantCultureIgnoreCase))
                return true;
    
            var request = controllerContext.RequestContext.HttpContext.Request;
            return request[methodInfo.Name] != null;
        }
    }
    

    Actions decorated with it:

    
    [HttpParamAction]
    public ActionResult Save(MyModel model)
    {
        // ...
    }
    
    [HttpParamAction]
    public ActionResult Publish(MyModel model)
    {
        // ...
    }
    

    HTML/Razor

    @using (@Html.BeginForm())
    {
        
        
        
    }
    

    name attribute of submit button should match action/method name

    This way you do not have to hard-code urls in javascript

提交回复
热议问题