开发者

ASP.Net MVC - Submit buttons with same value

I have a single form with multiple submit buttons that have same value. Example: "Proceed".

Now,开发者_运维技巧 in ASP.Net MVC's post controller method, how do I know which button is pressed?

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult DepartmentDetails(string submitButton)

The value of submitButton will always be "Proceed". How do I know which button is pressed.

I have given separate IDs for each button.

Thanks.


Try this:

<% using (Html.BeginForm())
   { %>
   <input type="submit" value="Submit" name="Submit1Button" />
   <input type="submit" value="Submit" name="Submit2Button" />
<%} %>

public class HomeController : Controller
{

    public ActionResult Index()
    {
        return View();
    }

    [AcceptVerbs(HttpVerbs.Post)]
    public ActionResult Index(FormCollection values)
    {
        string buttonName = values.AllKeys.Where((n) => n.EndsWith("Button")).SingleOrDefault();
        return View();
    }

}


Would it not make more sense to break your page into two different forms?

You can then use the arguments of your Html.BeginForm HtmlHelper method to specify different Controller(s) Action methods for each form.


I realise this question is ancient but just ran into it so thought I'd answer!

This is what we use:

/// <summary>
/// Attribute for Controller methods to decide whether a particular button
/// was clicked and hence whether the method can handle the action.
/// </summary>
public class IfButtonClickedAttribute : ActionMethodSelectorAttribute
{
    private readonly IEnumerable<string> _buttonNames;

    public IfButtonClickedAttribute(params string[] buttonNames)
    {
        _buttonNames = buttonNames;
    }

    public override bool IsValidForRequest(ControllerContext controllerContext, MethodInfo methodInfo)
    {
        if (controllerContext.HttpContext.Request.HttpMethod != "POST")
            return false;

        foreach (string buttonName in _buttonNames)
        {
            //this first test is for buttons or inputs that have the actual name specified
            if (controllerContext.HttpContext.Request.Form[buttonName] != null)
                return true;
        }

        return false;
    }
}

Then on your Actions you go:

[ActionName("SaveItem"), IfButtonClicked("SaveAsDraft")]
public ActionResult SaveAsDraft(){ ... }

[ActionName("SaveItem"), IfButtonClicked("SaveAsPublished")]
public ActionResult SaveAsPublished(){ ... }
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜