如何从按钮点击事件中调用具有复杂参数的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()" />
答案 0 :(得分:3)
如果您想使用按钮单击执行此操作,您可以订阅JS中按钮的单击事件。在你的JS中,你可以做一个ajax帖子,它会将JSON对象(你的VM)发布到你的行动中:
剃刀:
<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"
});
另一种方法是使用表单提交视图模型。
@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>
}
答案 1 :(得分:0)
您可以使用HTML表单
执行此操作<form action="@Url.Action("Export", "Report")" method="POST">
<input type="hidden" name="html" value="ADD YOUR HTML HERE">
<input type="button" value="Detail" />
</form>
在控制器内部,您需要使用html参数
[ValidateInput(false)]
[HttpPost]
public ActionResult Export(ViewModel vm, string html)
{
// some logic
}
答案 2 :(得分:0)
试试这个
<form action="@Url.Action("Export", "Report")" method="POST">
<input type="hidden" name="html" id="html" value="ADD YOUR HTML HERE">
<input type="button" id="btn1" value="Detail" />
</form>
在js中添加脚本
$("#btn1").click(function(){
$("#html").val($('#test').html());
})
在方法 string html
中添加param