Multiple Submit Buttons in MVC3 - FormCollection has no Key/Value for Input Type Submit - Remote Validation Issue?

前端 未结 5 579
不思量自难忘°
不思量自难忘° 2021-01-25 22:19

I have the two buttons in MVC3 application.

      
   

        
5条回答
  •  悲&欢浪女
    2021-01-25 23:13

    You might be able to get away with an ActionMethodSelectorAttribute attribute and override the IsValidForRequest method. You can see below this method just determines whether a particular parameter (Name) matches one of it's properties (Type). It should bind with a view model that looks like this:

    public class TestViewModel
    {
        public string command { get; set; }
        public string moreProperties { get; set; }
    }
    

    The attribute could look like this:

    public class AcceptSubmitTypeAttribute : ActionMethodSelectorAttribute
    {
        public string Name { get; set; }
        public string Type { get; set; }
    
        public override bool IsValidForRequest(ControllerContext controllerContext, MethodInfo methodInfo)
        {
            return controllerContext.RequestContext.HttpContext
                .Request.Form[this.Name] == this.Type;
        }
    }
    

    Then, you could tag your actions with the AcceptSubmitType attribute like this:

    [AcceptSubmitType(Name="command", Type="Transactions")]
    public ActionResult Index(TestViewModel vm) 
    {
        // use view model to do whatever
    }
    
    // to pseudo-override the "Index" action
    [ActionName("Index")]
    [AcceptSubmitType(Name="command", Type="All Transactions")]
    public ActionResult Index_All(TestViewModel vm) 
    {
        // use view model to do whatever
    }
    

    This also eliminates the need for logic in a single controller action since it seems you genuinely need two separate courses of action.

提交回复
热议问题