如何使用Ajax的链接,而不是提交按钮的形式?如何使用、而不是、按钮、形式

2023-09-10 14:06:29 作者:@考神

我有Ajax表格在我看来:

I have Ajax Form in my view:

 @using (Ajax.BeginForm("SearchHuman", "Search", new AjaxOptions(){
 InsertionMode = InsertionMode.Replace,
 UpdateTargetId = "result" }))   

{

<div class="editor-field">
@DescriptionStrings.Lastname: 
@Html.TextBox("LastName")
</div>

<div class="editor-field">
 @DescriptionStrings.Firstname:
 @Html.TextBox("Name")
</div>

//submit button
<input type="submit" value='Start Searching' />

//submit link
 @Ajax.ActionLink("search", "OtherSearch", new{lastName ="",...},  new AjaxOptions()
        {
            InsertionMode = InsertionMode.Replace,
            UpdateTargetId = "tab"
        })

}

我想有提交按钮和链接,2个不同的搜索(在不同的数据库)只用一种形式。但如何从窗体的文本框传递路线值到Ajax.ActionLink?

I want to have submit button and the link for 2 different searches (in different databases) using only one form. But how to pass route values from the textboxes of the form into Ajax.ActionLink?

在此先感谢!

推荐答案

我们选择是要实现一个自定义ActionMethodSelectorAttribute使我们能够区分哪个按钮是pressed根据其名称属性的解决方案。然后,我们布置了许多方法与ActionName装饰给他们所有相同的动作名称(在BeginFrom助手指定的),然后我们用我们的自定义ActionMethodSelector装饰来区分哪些方法是根据按钮的点击名字叫。最终结果是,每个提交按钮导致被称为一个单独的方法。

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.

有些code来说明:

在控制器:

[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
}

在视图中:

@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;
}