gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 04:00:57 25 4
gpt4 key购买 nike

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com