且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

向ASP.NET MVC控制器中的操作方法发出HttpPost请求

更新时间:2023-02-17 10:00:20

挑战我也想知道模型绑定器是否有办法 如果能够调用HttpPost,则会为我加载ViewModel对象 从第一个创建模板预览操作方法.

Challenge I am also wondering if there is a way that the model binder would load the ViewModel object for me if am able to call the HttpPost Preview action method from the first create template.

您可以使用标准格式或AJAX调用来调用Preview POST操作,然后传递视图模型的所有属性值.您在此请求中传递的所有值将是将由默认模型绑定程序绑定的值. 一篇文章解释了默认模型绑定程序如何期望为更复杂的结构命名参数例如列表和字典.

You could use either a standard form or an AJAX call to invoke the Preview POST action and pass all the property values of the view model then. All the values you pass in this request will be the values that will be bound by the default model binder. Here's an article explaining how the default model binder expects the parameters to be named for more complex structure such as lists and dictionaries.

使用AJAX的示例:

$.ajax({
    url: '@Url.Action("Preview")',
    type: 'POST',
    data: { Prop1: 'value 1', Prop2: 'value 2' },
    success: function(result) {
        // TODO: do something with the result returned from the POST action
    }
});

如果您不想使用AJAX,则可以使用带有隐藏字段的标准表单:

If you don't want to use AJAX you could use a standard form with hidden fields:

@using (Html.BeginForm())
{
    @Html.Hidden("Prop1", "value 1")
    @Html.Hidden("Prop2", "value 2")
    ...
    <button type="submit">Preview</button>
}