如何将数组从JavaScript传递到操作方法

时间:2022-05-02 22:50:39

I have the following View inside my ASP.Net mvc 3 web application:-

我的ASP中有如下的视图。Net mvc 3 web应用程序:-

@model IEnumerable<MvcApplication4.Models.Account>

@{
    ViewBag.Title = "customer";
}

<h3>Customers Info</h3>


    <script  type="text/javascript">

        $(function() {

            $("#MoveRight,#MoveLeft").click(function(event) {

                var id = $(event.target).attr("id");

                var selectFrom = id == "MoveRight" ? "#SelectLeft" : "#SelectRight";

                var moveTo = id == "MoveRight" ? "#SelectRight" : "#SelectLeft";



                var selectedItems = $(selectFrom + " :selected").toArray();

                $(moveTo).append(selectedItems);

                selectedItems.remove;

            });

        });

    </script>  

      <select id="SelectLeft" multiple="multiple">
 @foreach (var item2 in Model.OrderBy(a=>a.ORG_NAME)) {
            <option value = "@item2.ORG_ID" >@item2.ORG_NAME</option>




}
      </select>      

    <input id="MoveRight" type="button" value=" Add >> " />

  <input id="MoveLeft" type="button" value=" << Remove " /> 

      <select id="SelectRight" multiple="multiple">           

      </select>
 @Html.ActionLink("Next Page", "CustomersDetials", "Home", new {  }, null)//for testing only

But I am facing a problem in that I need to pass all the records which are inside the moveTo to the customersDetials action method by clicking on the "Next Page" action link. so can anyone suggest an approach which I can use to pass the items which are inside the moveto from my above view to my action method using the html.actionlink.

但我面临的问题是,我需要通过单击“下一页”操作链接,将mo一览表中的所有记录传递给customersDetials操作方法。因此,有人能提出一种方法,我可以使用html.actionlink将mo一览表中的项目从上面的视图传递给我的操作方法吗?

:::UPDATE:::

:::更新:::

I have added the following to the view:-

我在视图中添加了以下内容:-

@using (Html.BeginForm("CustomersDetials", "Home"))
{

      <select id="SelectLeft" multiple="multiple">
 @foreach (var item2 in Model.OrderBy(a=>a.ORG_NAME)) {
            <option value = "@item2.ORG_ID" >@item2.ORG_NAME</option>


}
      </select>      

    <input id="MoveRight" type="button" value=" Add >> " />

  <input id="MoveLeft" type="button" value=" << Remove " /> 



      <select id="SelectRight" name="SelectRight" multiple="multiple">           

      </select>
    <p>
<button type="submit">Next Page</button></p>

}

And then i have created the folloiwng ViewModel class to hole the values of the selected customers:-

然后我创建了folloiwng ViewModel类,将所选客户的值设为:-

public class SelectedCustomers
{
    public IEnumerable<Account> Info { get; set; }
}

then i added the folloiwng action method:-

然后我加入了folloiwng的作用方法:-

   public ActionResult CustomersDetials(string[] SelectRight)
        {
             foreach (var item in SelectRight) {

                // how to assign the values of the array to my viewmodel object       
        }

But i can not determine how i can assign the values of the array to the viewmodel object inside my action method.

但我无法确定如何将数组的值赋给action方法中的viewmodel对象。

:::UPDATE2:::

:::更新2:::

Here what i have ended up with. the action method looks like this:-

这就是我最后得到的。操作方法如下:-

    public ActionResult CustomersDetails(string[] SelectRight)
        {
            var selectedCustomers = new SelectedCustomers
            {
                Info = SelectRight.Select(GetAccount)
            };


        return View(selectedCustomers);

    }
    private Account GetAccount(string id)
    {


        return entities.Account.Find(id);
    }
}

And the folloiwng view:-

和folloiwng观点:-

@model MvcApplication4.Models.SelectedCustomers

@{
    ViewBag.Title = "CustomerDetials";
}

<h2>CustomerDetials</h2>
//code goes here

@foreach (var item in Model.Info) {
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.ORG_ID)
        </td>

but when i run the application i got the folloiwng error :-

但是当我运行这个应用程序时,我得到了一个错误:-

The type of one of the primary key values did not match the type defined in the entity. See inner exception for details.

On the:-

在:-

return entities.Account.Find(id);

::Solved:: i changed the string to be long in both the action method and GETAccount function.

我在action方法和GETAccount函数中都将字符串修改为long。

1 个解决方案

#1


2  

You could make the Next link a submit button of the form. Then when the form is submitted it will automatically send the selected items of the select lists to the server. It's the solution I would recommend you. Just put the select lists into a form and also don't forget to give your select lists names because that's what you will use in your controller action to retrieve the selected values:

您可以将下一个链接设置为表单的submit按钮。然后,当表单提交时,它会自动将选择列表中的选定项发送到服务器。这是我向你推荐的解决方案。只需将选择列表放入表单中,并且不要忘记给出选择列表的名称,因为您将在控制器操作中使用这个名称来检索所选的值:

@using (Html.BeginForm("CustomersDetials", "Home"))
{
    <select id="SelectLeft" name="SelectLeft" multiple="multiple">
        @foreach (var item2 in Model.OrderBy(a => a.ORG_NAME)) 
        {
            <option value="@item2.ORG_ID">@item2.ORG_NAME</option>
        }
    </select>

    <select id="SelectRight" name="SelectRight" multiple="multiple">           
    </select>

    <button type="submit">Next Page</button>
}

And by the way instead of doing those horrible foreach loops in your view to generate those multiple selectboxes you could use the built-in Html.ListBoxFor helper.

顺便说一下,不要在视图中做那些可怕的foreach循环来生成那些多重选择框你可以使用内置的Html。ListBoxFor帮手。

Now your controller action could look like this:

现在你的控制器动作可以是这样的:

[HttpPost]
public ActionResult CustomersDetials(string[] selectRight)
{
    ... the selectRight parameter will contain the selected values in the 
        corresponding select list
}

Another possibility to handle this case is to use AJAX:

处理这种情况的另一种可能是使用AJAX:

@Html.ActionLink("Next Page", "CustomersDetials", "Home", null, new { id = "next" })

and then:

然后:

$('#next').click(function() {
    $.ajax({
        url: this.href,
        type: 'POST',
        contentType: 'application/json;charset=utf-8',
        data: JSON.stringify(selectedItems),
        success: function(data) {

        }
    });
    return false;
});

Of course you need to make selectedItems a global variable, because right now you have declared it inside the click handler of the MoveRight, MoveLeft buttons. Otherwise this variable won't be accessible within the click event of the next link.

当然,您需要将selecteditem设置为全局变量,因为现在您已经在MoveRight MoveLeft按钮的单击处理程序中声明了它。否则,在下一个链接的单击事件中无法访问该变量。


UPDATE 1:

更新1:

Based on your update you could populate your view model like this:

基于您的更新,您可以填充您的视图模型如下:

public ActionResult CustomersDetials(string[] selectRight)
{
    var selectedCustomers = new SelectedCustomers
    {
        Info = selectRight.Select(GetAccount)
    };
    ... use your view model here
}

private Account GetAccount(string id)
{
    // TODO: given the selected ID go and fetch the corresponding
    // Account instance and return it here:

    return new Account
    {
        Id = id
    };
}

#1


2  

You could make the Next link a submit button of the form. Then when the form is submitted it will automatically send the selected items of the select lists to the server. It's the solution I would recommend you. Just put the select lists into a form and also don't forget to give your select lists names because that's what you will use in your controller action to retrieve the selected values:

您可以将下一个链接设置为表单的submit按钮。然后,当表单提交时,它会自动将选择列表中的选定项发送到服务器。这是我向你推荐的解决方案。只需将选择列表放入表单中,并且不要忘记给出选择列表的名称,因为您将在控制器操作中使用这个名称来检索所选的值:

@using (Html.BeginForm("CustomersDetials", "Home"))
{
    <select id="SelectLeft" name="SelectLeft" multiple="multiple">
        @foreach (var item2 in Model.OrderBy(a => a.ORG_NAME)) 
        {
            <option value="@item2.ORG_ID">@item2.ORG_NAME</option>
        }
    </select>

    <select id="SelectRight" name="SelectRight" multiple="multiple">           
    </select>

    <button type="submit">Next Page</button>
}

And by the way instead of doing those horrible foreach loops in your view to generate those multiple selectboxes you could use the built-in Html.ListBoxFor helper.

顺便说一下,不要在视图中做那些可怕的foreach循环来生成那些多重选择框你可以使用内置的Html。ListBoxFor帮手。

Now your controller action could look like this:

现在你的控制器动作可以是这样的:

[HttpPost]
public ActionResult CustomersDetials(string[] selectRight)
{
    ... the selectRight parameter will contain the selected values in the 
        corresponding select list
}

Another possibility to handle this case is to use AJAX:

处理这种情况的另一种可能是使用AJAX:

@Html.ActionLink("Next Page", "CustomersDetials", "Home", null, new { id = "next" })

and then:

然后:

$('#next').click(function() {
    $.ajax({
        url: this.href,
        type: 'POST',
        contentType: 'application/json;charset=utf-8',
        data: JSON.stringify(selectedItems),
        success: function(data) {

        }
    });
    return false;
});

Of course you need to make selectedItems a global variable, because right now you have declared it inside the click handler of the MoveRight, MoveLeft buttons. Otherwise this variable won't be accessible within the click event of the next link.

当然,您需要将selecteditem设置为全局变量,因为现在您已经在MoveRight MoveLeft按钮的单击处理程序中声明了它。否则,在下一个链接的单击事件中无法访问该变量。


UPDATE 1:

更新1:

Based on your update you could populate your view model like this:

基于您的更新,您可以填充您的视图模型如下:

public ActionResult CustomersDetials(string[] selectRight)
{
    var selectedCustomers = new SelectedCustomers
    {
        Info = selectRight.Select(GetAccount)
    };
    ... use your view model here
}

private Account GetAccount(string id)
{
    // TODO: given the selected ID go and fetch the corresponding
    // Account instance and return it here:

    return new Account
    {
        Id = id
    };
}