How to use ajax link instead of submit button for form?

假如想象 提交于 2019-12-01 13:51:35

The solution we opted for was to implement a custom ActionMethodSelectorAttribute which allowed us to differentiate which button was pressed based on its name property. We then decorated many methods with the ActionName decorator giving them all the same action name (the one specified in the BeginFrom helper), and then we used our custom ActionMethodSelector decorator to differentiate which method is to be called based on the name of the button clicked. The net result is that each submit button leads to a separate method being called.

Some code to illustrate:

In controller:

[ActionName("RequestSubmit")]
[MyctionSelector(name = "Btn_First")]
public ActionResult FirstMethod(MyModel modelToAdd)
{
    //Do whatever FirstMethod is supposed to do here
}

[ActionName("RequestSubmit")]
[MyctionSelector(name = "Btn_Second")]
public ActionResult SecondMethod(MyModel modelToAdd)
{
    //Do whatever SecondMethod is supposed to do here
}

In view:

@using (Ajax.BeginForm("RequestSubmit",.....
<input type="submit" id="Btn_First" name="Btn_First" value="First"/>
<input type="submit" id="Btn_Second" name="Btn_Second" value="Second"/>

As for the custom attribute:

public string name { get; set; }
public override bool IsValidForRequest(ControllerContext controllerContext, MethodInfo methodInfo)
{
    var btnName = controllerContext.Controller.ValueProvider.GetValue(name);
    return btnName != null;
}

But how to pass route values from the textboxes of the form into Ajax.ActionLink?

You can't. You should use a submit button if you want to send the values to the server. You could have 2 submit buttons in the same form which both submit to the same controller action. Then inside this action you can test which button was clicked and based on its value perform one or the other search.

Example:

<button type="submit" name="btn" value="search1">Start Searching</button>
<button type="submit" name="btn" value="search2">Some other search</button>

and then inside your controller action:

[HttpPost]
public ActionResult SomeAction(string btn, MyViewModel model)
{
    if (btn == "search1")
    {
        // the first search button was clicked
    }
    else if (btn == "search2")
    {
        // the second search button was clicked
    }

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