MVC 按钮点击调用 POST Action 方法

新手上路,请多包涵

如何从按钮单击事件调用具有复杂参数的 MVC 操作方法,如下所示?

 [ValidateInput(false)]
[HttpPost]
public ActionResult Export(ViewModel vm)
{
  // some logic
}

我已将其设为 POST 操作,因为我需要将按钮所在的当前页面的 HTML 标记传递给太长的操作方法。我试过这个,但这是一个 GET 操作

<input type="button" value="Detail" onclick="location.href='@Url.Action("Export", "Report")?html=' + $('#test').html()" />

原文由 CSharped 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 546
1 个回答

如果您想使用按钮单击来执行此操作,您可以在 JS 中订阅按钮的单击事件。在你的 JS 中,你可以做一个 ajax post,它将一个 JSON 对象(你的 VM)发布到你的操作:

剃刀:

 <input type="button" value="Detail" id="buttonId" />

记者:

     $('#buttonId').click(function () { //On click of your button

    var property1 = $('#property1Id').val(); //Get the values from the page you want to post
    var property2 = $('#property2Id').val();

    var JSONObject = { // Create JSON object to pass through AJAX
Property1: property1, //Make sure these names match the properties in VM
Property2: property2
};

    $.ajax({ //Do an ajax post to the controller
        type: 'POST',
        url: './Controller/Action',
        data: JSON.stringify(JSONObject),
        contentType: "application/json; charset=utf-8",
        dataType: "json"
        });

另一种方法是使用表单提交视图模型。

     @using (Html.BeginForm("ActionName", "ControllerName", FormMethod.Post))
{
    @Html.AntiForgeryToken()

<div class="form-horizontal">

    @Html.ValidationSummary(true, "", new { @class = "text-danger" })

    <div class="form-group">
        @Html.LabelFor(model => model.PropertyName1, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            <input type="text" id="PropertyName1" name="PropertyName1" class="form-control"  />
            @Html.ValidationMessageFor(model => model.PropertyName1, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.PropertyName2, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.PropertyName2, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.PropertyName2, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        <div class="col-md-offset-2 col-md-10">
            <input type="submit" value="Button text" class="btn btn-primary" />
        </div>
    </div>
    </div>
}

原文由 j9070749 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题