Posting same form to different actions depending on button clicked

六月ゝ 毕业季﹏ 提交于 2019-12-19 20:15:11

问题


I have a similar post on this on StackOverflow but perhaps my misunderstanding is more substantial. I have an action Index() and an Index view its rendering. From Index() view depending on the button clicked [HttpPost]Index() or [HttpPost]Search() must be called cause I'm posting some data. Is the only way to post to different actions is by using jQuery ? If jQuery is the only way, if my actions return views(complete Html pages), to I have to clean the whole document element from the $.post and fill it up with my views html ? I'm pretty new to all this, thanks a ton!

@using (Html.BeginForm())
{
    <input name="startDate" type="text" size="20" class="inputfield" id="datepicker" />
    <a href="#" id="apply_button">...</a>
    <a href="#" id="go_button">...</a>
}


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

//Perhaps this action is needed
[HttpPost]
public ActionResult Index(string lang, string startDate)
{
    return View();
}

[HttpPost]
public ActionResult Search(string lang, string startDate)
{
    return View();
]

回答1:


You can change the form's action attribute depending on which button was clicked.

e.g. To post to the 'search' action when the 'go' button is clicked:

$('#go_button').click(function() {
    $('form').attr("action", "Search");  //change the form action
    $('form').submit();  // submit the form
});



回答2:


Additional to accepted answer when you are in need to change action as well as Controller too:

$('#go_button').click(function() {
    $('form').attr("action", "@("Search","OtherControllerName")");  //change the form action
    $('form').submit();  // submit the form
});


来源:https://stackoverflow.com/questions/7508233/posting-same-form-to-different-actions-depending-on-button-clicked

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!