简体   繁体   English

MVC:将值从视图传递到控制器

[英]MVC: Passing Value from View to Controller

I am trying to pass values from a view to a controller in MVC. 我试图将值从视图传递到MVC中的控制器。 I am using a ViewModel and normally the values would bind to the properties as long as the names are the same. 我使用的是ViewModel,通常只要名称相同,值就会绑定到属性。 However because the values are generated via a foreach loop the names of the values do not match the names of the properties in the view model. 但是,因为值是通过foreach循环生成的,所以值的名称与视图模型中属性的名称不匹配。

I am working around this by assigning the values to a variable in Razor. 我正在通过将值分配给Razor中的变量来解决此问题。 However one of my values is in a text box on the form and the value is not being passed to the controller and I cannot work out why. 但是,我的值之一是在表单上的文本框中,并且该值未传递给控制器​​,因此我无法弄清原因。

I get a null exception when clicking the button. 单击按钮时出现空异常。

VIEW Code is below: VIEW代码如下:

@model PagedList.IPagedList<Mojito.Domain.ViewModels.ShoppingCartProductItem>
@using System.Web.UI.WebControls
@using PagedList.Mvc;
<link href="~/Content/PagedList.css" rel="stylesheet" type="text/css" />
@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<h2>Mojito Products</h2>

<table class="table">
    <tr>
        <th>
            @Html.DisplayNameFor(model => model.FirstOrDefault().Description)
        </th>

        <th>
            @Html.ActionLink("Price", "Index", new { sortOrder = ViewBag.SortByPrice, currentFilter = ViewBag.CurrentFilter })
        </th>
        <th>
            @Html.DisplayNameFor(model => model.FirstOrDefault().Quantity)
        </th>
        <th>

        </th>

        <th></th>
    </tr>

    @foreach (var item in Model)
    {
        <tr>

            <td>
                @Html.DisplayFor(modelItem => item.Description)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.Price)
            </td>
            <td>
                @Html.TextBoxFor(modelItem => item.Quantity)
            </td>


            <td>
                @{string Description = item.Description;}
                @{decimal Price = item.Price;}
                @{int Quantity = item.Quantity; }

                @using (Html.BeginForm("AddToCart", "ShoppingCart", FormMethod.Post))
                {
                    <div class="pull-right">
                        @if (Request.Url != null)
                        {
                            <input type="text" hidden="true" name="Description" value=@Description />
                            <input type="text" hidden="true" name="Price" value=@Price />
                            <input type="text" hidden="true" name="Quantity" value=@Quantity />
                            @Html.Hidden("returnUrl", Request.Url.PathAndQuery)
                            <input type="submit" class="btn btn-success" value="Add to cart" />
                        }

                    </div>
                }
            </td>
        </tr>
    }


</table>
<div class="col-md-12">
    Page @(Model.PageCount < Model.PageNumber ? 0 : Model.PageNumber) of @Model.PageCount
</div>
@Html.PagedListPager(Model, page => Url.Action("Index",
        new { page, sortOrder = ViewBag.CurrentSort, currentFilter = ViewBag.CurrentFilter }))

Controller Code below 下面的控制器代码

public ActionResult AddToCart(Cart cart, MojitoProduct product, string returnUrl, int Quantity =1)
        {

            if (product != null)
            {
                cart.AddItem(product, Quantity);
            }
            return RedirectToAction("Index", new { returnUrl });
        }

Do not use foreach. 不要使用foreach。 Use a for-loop instead and within this, qualify the full path to your properties using the index. 改用for循环,在此循环中,使用索引限定属性的完整路径。

Better yet: use a Edit- or DisplayTemplate for the ShoppingCartProductItem . 更好的是:对ShoppingCartProductItem使用Edit或DisplayTemplate。 This will also keep your path. 这也将保持您的道路。

You have to use for loop instead of foreach: 您必须使用for循环而不是foreach:

@for (int i=0;i < Model.Count; i++)
{
        <tr>

            <td>
                @Html.DisplayFor(modelItem => Model[i].Description)
            </td>
            <td>
                @Html.DisplayFor(modelItem => Model[i].Price)
            </td>
            <td>
                @Html.TextBoxFor(modelItem => Model[i].Quantity)
            </td>
    ..........................
    ..........................
    ..........................
}

you can also post all using one form by posting List<ShoppingCartProductItem> , see Model Binding To A List 您还可以通过发布List<ShoppingCartProductItem>来使用一种表单来发布所有表单,请参阅模型绑定到列表

Your textboxes so values out of the form. 您的文本框使值超出了表单。

Try like below 尝试如下

@using (Html.BeginForm("AddToCart", "ShoppingCart", FormMethod.Post))
{
    @foreach (var item in Model)
    {
        <tr>

            <td>
                @Html.DisplayFor(modelItem => item.Description)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.Price)
            </td>
            <td>
                @Html.TextBoxFor(modelItem => item.Quantity)
            </td>


            <td>
                @{string Description = item.Description;}
                @{decimal Price = item.Price;}
                @{int Quantity = item.Quantity; }


                    <div class="pull-right">
                        @if (Request.Url != null)
                        {
                            <input type="text" hidden="true" name="Description" value=@Description />
                            <input type="text" hidden="true" name="Price" value=@Price />
                            <input type="text" hidden="true" name="Quantity" value=@Quantity />
                            @Html.Hidden("returnUrl", Request.Url.PathAndQuery)
                            <input type="submit" class="btn btn-success" value="Add to cart" />
                        }

                    </div>

            </td>
        </tr>
    }
}

I resolved this in the short term by using new and forcing the name of the parameter. 我通过使用new并强制使用参数名称在短期内解决了此问题。

@Html.HiddenFor(modelItem => t.NoOfUsers, new { Name = "NoOfUsers", id = "NoOfUsers" }) @ Html.HiddenFor(modelItem => t.NoOfUsers,新的{名称=“ NoOfUsers”,id =“ NoOfUsers”})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM