asp.net-mvc 使用 html.actionlink 将模型从视图传递到控制器

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13750556/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 02:27:15  来源:igfitidea点击:

pass model from view to controller with html.actionlink

asp.net-mvcasp.net-mvc-3razorasp.net-mvc-4

提问by Laziale

I am trying to get the model data from a strongly typed view to a controller. Using the submit button is ok, I can get the data. Now I want to achieve the same with html.actionlink. This is what I have: View:

我正在尝试将模型数据从强类型视图获取到控制器。使用提交按钮没问题,我可以获取数据。现在我想用 html.actionlink 实现同样的效果。这就是我所拥有的: 查看:

@model WordAutomation.Models.Document    
    @{
        ViewBag.Title = "Document";
    }
      <script type="text/javascript">
          $(function () {
              $("#dialog").dialog();
          });
        </script>

    <h2>Document</h2>

    @using (Html.BeginForm()) {
        @Html.ValidationSummary(true)

        <fieldset>
            <legend>Document</legend>

            <div class="editor-label">
                @Html.LabelFor(model => model.ClientTitle)
            </div>
            <div class="editor-field">
                @Html.EditorFor(model => model.ClientTitle)
                @Html.ValidationMessageFor(model => model.ClientTitle)
            </div>

            <div class="editor-label">
                @Html.LabelFor(model => model.ClientFullName)
            </div>
            <div class="editor-field">
                @Html.EditorFor(model => model.ClientFullName)
                @Html.ValidationMessageFor(model => model.ClientFullName)
            </div>

            <div class="editor-label">
                @Html.LabelFor(model => model.ClientCustomSSN)
            </div>
            <div class="editor-field">
                @Html.EditorFor(model => model.ClientCustomSSN)
                @Html.ValidationMessageFor(model => model.ClientCustomSSN)
            </div>

            <p>
                <input type="submit" value="Create" />            
            </p>
        </fieldset>
    }

    <div>
        @Html.ActionLink("Preview", "PreviewWordDocument", "Home", null, new { id = "previewLink" })    

    </div>

    <div id="dialogcontainer">
        <div id="dialogcontent"><input type="submit" value="Create" />        </div>
    </div>

    @section Scripts {

        <script type="text/javascript">

                $(document).ready(function() {

                    $("#dialogcontainer").dialog({
                        width: 400,
                        autoOpen:false,
                        resizable: false,
                        title: 'Test dialog',
                        open: function (event, ui) {
                            $("#dialogcontent").load("@Url.Action("PreviewWordDocument", "Home")");
                        },
                        buttons: {
                            "Close": function () {
                                $(this).dialog("close");
                            }
                        }
                    });

                    $("#previewLink").click(function(e) {
                        e.preventDefault();
                        $("#dialogcontainer").dialog('open');
                    });

                });

            </script>
    }

Controller:

控制器:

public ActionResult Document()
        {      
            return View();
        }

        [HttpPost]
        public ActionResult Document(WordAutomation.Models.Document model)
        {
            Models.Utility.EditWord word = new Models.Utility.EditWord();
            word.EditWordDoc(model);
            return View("Display", model);
        }

        public ActionResult PreviewWordDocument()
        {           
            var image = Url.Content("~/Content/preview.jpeg");

            return PartialView((object)image);
        } 

The document actionresult can get the model, but I want to know how can I get the values from the actionlink which will trigger the PreviewWordDocument action.

文档 actionresult 可以获取模型,但我想知道如何从将触发 PreviewWordDocument 操作的 actionlink 获取值。

Thanks in advance, Laziale

提前致谢, Laziale

采纳答案by Daniel J.G.

The form can only be posted using the submit button to the URL given by its action attribute.

表单只能使用提交按钮发布到其 action 属性给出的 URL。

You can however send the form data to a different URL using the jQuery post method, manually validating the form before it is sent. That way you can send the form data to the PreviewWordDocument controller method and handle the response in order to show the preview in the desired div. (It will be helpful if you give an id to the form, so you can easily find it using jQuery)

但是,您可以使用 jQuery post 方法将表单数据发送到不同的 URL,在发送之前手动验证表单。这样您就可以将表单数据发送到 PreviewWordDocument 控制器方法并处理响应,以便在所需的 div 中显示预览。(如果你给表单一个 id 会很有帮助,这样你就可以使用 jQuery 轻松找到它)

So your click event handler for the preview link will look like this:

因此,预览链接的点击事件处理程序将如下所示:

$("#previewLink").click(function(e) {
    e.preventDefault();
    if($("#YourFormId").valid()){
        $("#dialogcontainer").dialog('open');
    }
});

In the open function of the dialog you will post the form (which was already validated) to the preview controller method, using the jQuery ajax function. The response will be loaded into the dialogContent div:

在对话框的 open 函数中,您将使用 jQuery ajax 函数将表单(已经过验证)发布到预览控制器方法。响应将加载到 dialogContent div:

    $.ajax({
        type: "POST",
        url: $("#previewLink").attr("href"), //the preview controller method
        data: $("#YourFormId").serialize(), 
        success: function (data) {
            //load ajax response into the dialogContent div
            $("#dialogcontent").html(data);
        },
        error: function(xhr, error) {
            $("#YourFormId").prepend('<div id="ajaxErrors"></div>')
                            .html(xhr.responseText);
        }
    });

Now you will now be able to receive the whole document in the PreviewWordDocument action:

现在,您现在可以在 PreviewWordDocument 操作中接收整个文档:

public ActionResult PreviewWordDocument(WordAutomation.Models.Document model)
{           
    var image = Url.Content("~/Content/preview.jpeg");

    return PartialView((object)image);
} 

回答by Behnam Esmaili

in a HTML page when you click on a submit button all the input elements inside the form which the submit button resides in will posted to server, but when you click on a anchor (<a>tag ). you only send a request with a Get method and without posting any value.but if you want to send particular value to the server with this approach you can do it by query string.you have used following to make a request :

在 HTML 页面中,当您单击提交按钮时,提交按钮所在的表单内的所有输入元素都将发布到服务器,但是当您单击锚点(<a>标记)时。您只使用 Get 方法发送请求,而没有发布任何值。但是如果您想使用这种方法向服务器发送特定值,您可以通过查询字符串来完成。您已使用以下方法发出请求:

     @Html.ActionLink("Preview", "PreviewWordDocument", "Home", null, 
     new { id = "previewLink" })

this will produce :

这将产生:

<a id="previewLink" href="/Home/PreviewWordDocument"> Preview </a>

which is incorrect.to pass any value to the server with ActionLinkuse 4th parameter like this :

这是不正确的。ActionLink使用第 4 个参数将任何值传递给服务器,如下所示:

     @Html.ActionLink("Preview", "PreviewWordDocument", "Home",
     new { id = "previewLink" }, null)

the result from this code would be :

这段代码的结果是:

 <a href="/Home/PreviewWordDocument?id=previewLink"> Preview </a>

cheers!

干杯!