asp.net-mvc ASP.NET MVC 将数据从视图传递到控制器

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1013468/
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-07 23:39:39  来源:igfitidea点击:

ASP.NET MVC Passing Data from View to Controller

asp.net-mvc

提问by Lukasz

I have a view with a grid that contains items added to a workstation. The user can select an item from a drop down list and click an action link which calls a controller that adds that item to the workstation. I can make it work by reading the FormCollection object in the Post action of the controller.

我有一个网格视图,其中包含添加到工作站的项目。用户可以从下拉列表中选择一个项目,然后单击一个操作链接,该链接调用一个控制器,将该项目添加到工作站。我可以通过读取控制器 Post 操作中的 FormCollection 对象来使其工作。

<p>
    <% using(Html.BeginForm("AddItem", "Home")) { %>
    <label for="ItemID">Item:</label>
    <%= Html.DropDownList("ItemID", Model.ItemsList) %>
    <%= Html.Hidden("WorkstationID", Model.Workstation.RecordID) %>
    <input type="submit" value="Submit" />
    <% } %>
</p>


[AcceptVerbs(HttpVerbs.Post)]
public ActionResult AddItem(FormCollection formValue)
{
    long workstationId = Convert.ToInt64(formValue["WorkstationID"]);
    long itemId = Convert.ToInt64(formValue["ItemID"]);

    Workstation workstation = itilRepository.FindWorkstation(workstationId);
    Item item = itilRepository.FindItem(itemId);

    itilRepository.AddItem(workstation, item);
    itilRepository.Save();

    return Content("Item added successfully!");
}

What I want to do is be able to submit the two parameters the workstationId and itemId to the controller using Ajax.ActionLink and have the new item that was added get inserted into the grid. I am rendering the grid like this:

我想要做的是能够使用 Ajax.ActionLink 将两个参数workstationId 和itemId 提交给控制器,并将添加的新项目插入到网格中。我正在像这样渲染网格:

<table>
      <tr>
        <th></th>
      <th>
        Name
      </th>
      <th>
        Service Tag
      </th>
      <th>
        Serial Number
      </th>
    </tr>

    <% foreach (var item in Model.Items) { %>

    <tr>
      <td>
        <%= Html.ActionLink("Edit", "ItemEdit", new { id = item.RecordID }) %> |
        <%= Html.ActionLink("Details", "ItemDetails", new { id = item.RecordID   })%>
      </td>
      <td>
        <%= Html.Encode(item.Name) %>
      </td>
      <td>
        <%= Html.Encode(item.ServiceTag) %>
      </td>
      <td>
        <%= Html.Encode(item.SerialNumber) %>
      </td>
    </tr>

    <% } %>

</table>

The problem I have is when I submit using the ActionLink I can't figure out how to pass in the parameters to the controller and how to update the grid without reloading the entire view.

我遇到的问题是,当我使用 ActionLink 提交时,我不知道如何将参数传递给控制器​​以及如何在不重新加载整个视图的情况下更新网格。

I would really appreciate some help with this or even a link to a tutorials that does something similar.

我真的很感激这方面的一些帮助,甚至是一个指向做类似事情的教程的链接。

Thank You!

谢谢你!

This is the working version, the one problem is that when the controller returns the partial view that is all that gets rendred the actual page is gone.

这是工作版本,一个问题是当控制器返回部分视图时,实际页面已经消失了。

<% using (Ajax.BeginForm("AddItem", null, 
        new AjaxOptions
        {
            UpdateTargetId = "ResultsGoHere",
            InsertionMode = InsertionMode.Replace
        }, 
        new { @id = "itemForm" } ))
{ %>

    <label for="ItemID">Item:</label>
    <%= Html.DropDownList("itemId", Model.ItemsList) %>
    <%= Html.Hidden("workstationId", Model.Workstation.RecordID) %>

    <a href="#" onclick="$('#itemForm').submit();">Submit</a>

    <div id="ResultsGoHere">
        <% Html.RenderPartial("WorkstationItems", Model.Items); %>
    </div>

<% } %>

Not sure what the cause is, the replace was working correctly before but the controller wasn't getting the drop down value. Now the controller is getting the value but the partial view that is returned replaces the entire page.

不知道是什么原因,更换之前工作正常,但控制器没有得到下拉值。现在控制器正在获取值,但返回的部分视图替换了整个页面。

The Action Method:

动作方法:

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult AddItem(string workstationId, string itemId)
{
    long lworkstationId = Convert.ToInt64(workstationId);
    long litemId = Convert.ToInt64(itemId);

    Workstation workstation = itilRepository.FindWorkstation(lworkstationId);
    Item item = itilRepository.FindItem(litemId);

    IQueryable<Item> items = itilRepository.AddItem(workstation, item);
    itilRepository.Save();

    return PartialView("WorkstationItems", items);
}

This is the HTML for the View that does all the work:

这是完成所有工作的视图的 HTML:

<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<ITILDatabase.Models.WorkstationFormViewModel>" %>

<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
    Workstation Details
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">

    <script src="/Scripts/MicrosoftAjax.js" type="text/javascript"></script>
    <script src="/Scripts/MicrosoftMvcAjax.js" type="text/javascript"></script>
    <link type="text/css" href="/../Content/css/ui-lightness/jquery-ui-1.7.2.custom.css" rel="stylesheet" />    
    <script type="text/javascript" src="/../Content/js/jquery-1.3.2.min.js"></script>
    <script type="text/javascript" src="/../Content/js/jquery-ui-1.7.2.custom.min.js"></script>

    <h2>
        Workstation Details</h2>
    <fieldset>
        <legend>Fields</legend>
        <p>
            Record ID:
            <%= Html.Encode(Model.Workstation.RecordID) %>
        </p>
        <p>
            Name:
            <%= Html.Encode(Model.Workstation.Name) %>
        </p>
        <p>
            Description:
            <%= Html.Encode(Model.Workstation.Description) %>
        </p>
        <p>
            Site:
            <%= Html.Encode(Model.Workstation.Site.Name) %>
        </p>
        <p>
            Modified By:
            <%= Html.Encode(Model.Workstation.ModifiedBy) %>
        </p>
        <p>
            Modified On:
            <%= Html.Encode(String.Format("{0:g}", Model.Workstation.ModifiedOn)) %>
        </p>
        <p>
            Created By:
            <%= Html.Encode(Model.Workstation.CreatedBy) %>
        </p>
        <p>
            Created On:
            <%= Html.Encode(String.Format("{0:g}", Model.Workstation.CreatedOn)) %>
        </p>
    </fieldset>
    <fieldset>
        <legend>People</legend>
        <% Html.RenderPartial("WorkstationPeople", Model.People); %>
    </fieldset>
    <fieldset>
        <legend>Positions</legend>
        <% Html.RenderPartial("WorkstationPositions", Model.Positions); %>
    </fieldset>
    <fieldset>
        <legend>Items</legend>

            <% using (Ajax.BeginForm("AddItem", "Home", null, 
                    new AjaxOptions
                    {
                        UpdateTargetId = "ResultsGoHere",
                        InsertionMode = InsertionMode.Replace
                    }, 
                    new { @id = "itemForm" } ))
            { %>

                <label for="ItemID">Item:</label>
                <%= Html.DropDownList("itemId", Model.ItemsList) %>
                <%= Html.Hidden("workstationId", Model.Workstation.RecordID) %>

                <a href="#" onclick="$('#itemForm').submit();">Submit</a>

                <div id="ResultsGoHere">
                    <% Html.RenderPartial("WorkstationItems", Model.Items); %>
                </div>

            <% } %>
    </fieldset>
    <br />
    <p>
        <%=Html.ActionLink("Edit", "WorkstationEdit", new { id = Model.Workstation.RecordID }) %>
        |
        <%=Html.ActionLink("Back to List", "Index") %>
    </p>
</asp:Content>

回答by Tomas Aschan

What result are you expecting from the AJAX call?

您期望 AJAX 调用的结果是什么?

You could use the AjaxHelperobject's helper methods instead of the HtmlHelperto render the link. For example, to get new content with an AJAX HttpPOST call and insert it into a <div>with the id set to ResultsGoHereyou render the following link:

您可以使用AjaxHelper对象的辅助方法而不是HtmlHelper来呈现链接。例如,要使用 AJAX HttpPOST 调用获取新内容并将其插入<div>id 设置为ResultsGoHere您呈现以下链接:

<%= Ajax.ActionLink("Edit", "ItemEdit", 
                         new {
                             itemId = item.RecordId, 
                             workstationId = myWorkStationId
                         },
                         new AjaxOptions {
                             HttpMethod="POST",
                             UpdateTargetId="ResultsGoHere",
                             InsertionMode = InsertionMode.Replace 
                         }) %>

In your AcionMethod, you can simply test on Request.IsAjaxRequest()to decide what to return:

在您的 中AcionMethod,您可以简单地测试Request.IsAjaxRequest()以决定返回什么:

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult ItemEdit(string itemId, string workstationId) {
    // edit the item and get it back

    if (Request.IsAjaxRequest()) {
        return PartialView("SingleItem", item);
    }
    return RedirectToAction("ItemEdit", new { itemId = item.RecordId, workstationId = workstationId });
}

// fallback for get requests
public ActionResult ItemEdit(string itemId, string workstationId)
{
    // do stuff and return view
}

回答by Tomas Aschan

This is how you could do it using the Ajax.BeginForm()method instead:

这是您可以使用该Ajax.BeginForm()方法来执行此操作的方法:

<% using (Ajax.BeginForm("ItemEdit", null, new AjaxOptions
            {
                UpdateTargetId = "ResultsGoHere",
                InsertionMode = InsertionMode.Replace
            }, new { @id = "itemForm" } )
{ %>
<p>
    <%= Html.DropDownList("itemId") %></p>
<p>
    <%= Html.DropDownList("workstationId") %></p>
<p>
    <a href="#" onclick="$('#itemForm').submit();">Submit</a>
</p>
<% } %>

Please note that the code is in its current state in no way fully functional - the dropdownlists don't get their items from anywhere, there is no <div>to take care of the results from the AJAX request, and the onclickattribute on the link that submits the form requires that jQuery is included (in which case it is way better to give the link an id and add a click()event handler to it from a separate jsfile...)

请注意,该代码处于其当前状态,并没有完全发挥作用 - 下拉列表不会从任何地方获取它们的项目,无需<div>处理 AJAX 请求的结果,以及onclick提交表单要求包含 jQuery(在这种情况下,最好为链接提供一个 id 并click()从单独的js文件向其添加一个事件处理程序...)

EDIT: Oh, and I haven't verified that it is OK to pass a nullvalue to the routeValuesparameter. If not, just supply the controller and action names, and you'll be fine.

编辑:哦,我还没有验证可以将null值传递给routeValues参数。如果没有,只需提供控制器和操作名称,就可以了。

回答by h3n

how can you pass the model from the view to the post create action of the controller using ajax.actionlink?

如何使用 ajax.actionlink 将模型从视图传递到控制器的创建后操作?

回答by Harikrishna Getukati

Here, as of my knowledge, we can pass data from View to Controller in two ways...

在这里,据我所知,我们可以通过两种方式将数据从视图传递到控制器......

  1. Using Formcollectionbuilt in keyword like this..

    [HttpPost]
    public string filter(FormCollection fc)
    {
        return "welcome to filtering : "+fc[0];
                        (or)
        return "welcome to filtering : "+fc["here id of the control in view"];
    
    }
    
  1. Formcollection像这样使用内置关键字..

    [HttpPost]
    public string filter(FormCollection fc)
    {
        return "welcome to filtering : "+fc[0];
                        (or)
        return "welcome to filtering : "+fc["here id of the control in view"];
    
    }
    

FormCollectionwill work only when you click any button inside a form. In other cases it contains only empty data

FormCollection仅当您单击表单内的任何按钮时才有效。在其他情况下,它只包含空数据

  1. Using model class

    [HttpPost]
    public string filter(classname cn)
    {
        return "welcome to filtering : "+cn.Empid+""+cn.Empname;
    }
    
  1. 使用模型类

    [HttpPost]
    public string filter(classname cn)
    {
        return "welcome to filtering : "+cn.Empid+""+cn.Empname;
    }
    

回答by venkatesh mahendru

This is how you will be able to send multiple parameters through actionLink.
For this situation please refer to the code below:

这就是您将能够通过 actionLink 发送多个参数的方式。
对于这种情况,请参考以下代码:

@Html.ActionLink("Link text", "Action Name", null, routeValues: new { pram_serviceLine = Model.ServiceLine_ID, pram_Month = Model.Month, pram_Year = Model.Year, flag = "ROTATION" }

Reply if it works.

如果有效请回复。