开发者

MVC - get button id on form post

I have a form with multiple buttons. On post, I would like to get the id of the button that was actually pressed.

So for instance if button #2 is pressed, I need to be able to access the id for开发者_JAVA百科 this button and then delete itemid 2:

<button name="button" value="DeletePollAnswer" id="Delete1">Delete</button>
<button name="button" value="DeletePollAnswer" id="Delete2">Delete</button>

Is this possible? How would you do that in the controler?

Thanks


It sounds like you are going around this the wrong way, generally when forms are submitted it is in key value pairs, with the key being the element name attribute and the value being the element value attribute. If you need to differentiate I would do it there.

IE:

<button name="Delete1" value="DeletePollAnswer" id="Delete1">Delete</button>
<button name="Delete2" value="DeletePollAnswer" id="Delete2">Delete</button>

Also with MVC it is likely you might want links that would want to call a specific action or pass data to a specific action in which case the an anchor with a an action link should be invoking the specific action directly.

IE:

<%= Html.ActionLink("Delete Poll Answer", "SomeDeleteAction", "SomePollController", new { pollID = somePollIDValue }, null); %>

Of course in that example all the names are completely gibberish, you would want to replace with your controller/action/params etc.


View:

<script language="javascript" type="text/javascript">
    function SubmitForm(id)
    {
        document.forms[0].action = 'ActionName/' + id;
        document.forms[0].submit();
    }
</script>
<% Html.BeginForm("", "", FormMethod.Post); %>
<input id="btn1" type="button" value="Ok" onclick="javascript:SubmitForm('btn1')" />
<input id="btn2" type="button" value="Cancel" onclick="javascript:SubmitForm('btn2')" />
<% Html.EndForm(); %>

Controller:

public ActionResult ActionName(string id)
{
    if (id == "btn1")
        //Exec(xxx);
    else
        //Exec(yyy);
        return View();
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜