c# - MVC按钮点击调用POST Action方法

标签 c# jquery html asp.net-mvc

如何从按钮单击事件调用具有复杂参数的 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()" />

最佳答案

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

Razor :

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

JS:

    $('#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"
        });

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

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

关于c# - MVC按钮点击调用POST Action方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44136636/

相关文章:

html - Google 未列出网站,但没有错误且内容显得丰富

c# - JWT 总是在 .net 核心 api 上返回未经授权的 401

c# - 将图 A 更改为图 B

c# - Windows Phone 8.1 自定义键盘

c# - StackPanel 的一侧有一个按钮,另一侧有其他按钮

jQuery 验证插件 : accept letters only?

javascript - jQuery:如何检测页面是否被ajax请求调用

javascript - 隐藏所有具有相同类的 div,但单击并更改文本

html - 如何根据屏幕尺寸重新排序 <OL> (bootstrap 4)

php - php中检测ie10、<ie10等浏览器