【问题标题】:Getting model name attribute wrongly in forms c#在表单c#中错误地获取模型名称属性
【发布时间】:2021-03-17 17:16:30
【问题描述】:

我弄错了我的型号名称 而不是这样

<input class="text-box single-line" data-val="true" data-val-required="آدرس دریافت محصول اجباری میباشد." id="Address" name="Address" type="text" value="">

它是这样渲染的

<input class="text-box single-line" data-val="true" data-val-required="آدرس دریافت محصول اجباری میباشد." id="mod_Address" name="mod.Address" type="text" value="">

我的模型是这样定义的:

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
using identity2.Models;


namespace identity2.ViewModels
{
    public class OrderIndexViewModel
    {
        public products Product { get; set; }

        public int Count_order { get; set; }

        [Required(ErrorMessage = "آدرس دریافت محصول اجباری میباشد.")]
        [Display(Name = "آدرس دریافت محصول")]
        public string Address { get; set; }


        [Display(Name = "سفارش به صورت آفلاین")]
        public bool OfflineOrder { get; set; }

        [Required(ErrorMessage = "تاریخ دریافت محخول را انتخاب کنید")]
        [Display(Name = "تاریخ دریافت محصول")]
        [RegularExpression(@"^([1][34]\d{2}\/((1[0-2]|[1-9]))\/(3[01]|[12][0-9]|[1-9]))$", ErrorMessage = "تاریخ معتبر نمیباشد")]

        public string recive_date { get; set; }


    }
}

我的看法:

@model IList<identity2.ViewModels.OrderIndexViewModel>
@using System.Globalization;
@using identity2.Models;
@{
                var mod = Model[0];
                var dt = DateTime.Now;
                PersianCalendar pc = new PersianCalendar();
                var timenow = @pc.PearsianDate(dt);
}

<h4>سبد خرید</h4>
<div class="alert alert-warning alert-dismissible fade show" role="alert">
    <strong>توجه!</strong> <p>کلیه محصولات در روز پنج شنبه از ساعت 13 الی  19 به صورت رایگان ارسال میگردد در غیر این صورت هزینه پیک بر عهده مشتری می باشد.</p>
    <button type="button" class="close" data-dismiss="alert" aria-label="Close">
        <span aria-hidden="true">&times;</span>
    </button>
</div>
<table class="table table-responsive">
    <tr>
        <th>نام محصول</th>
        <th>تعداد سفارش </th>
        <th>قیمت کل</th>
        <th>عملیات</th>
    </tr>
    @if (Model != null)
    {

        foreach (var protoype in Model)
        {


            var totalprice = @protoype.Product.price * @protoype.Count_order;
            <tr>
                <td>
                    @protoype.Product.title
                </td>
                <td>
                    @protoype.Count_order
                </td>
                <td>
                    @totalprice تومان
                </td>
                <td>
                    <a href="@($"/Order/DiscardOrder/{protoype.Product.id}")" )><i class="fa fa-times" aria-hidden="true"></i></a>

                </td>

            </tr>


        }//end foreach
    }

</table>
<div class="row">
    <div class="col">
        <h3>سفارش آنلاین</h3>
        @using (Html.BeginForm("CartPaymentPost", "Order", FormMethod.Post, new { enctype = "multipart/form-data" }))

        {
            @Html.AntiForgeryToken()

            <div class="row">
                <div class="col-md-6">
                    @if (!ViewData.ModelState.IsValid)
                    {
                        @Html.ValidationSummary("", new { @class = "alert alert-warning alert-dismissible fade show" })
                    }
                </div>

            </div>

            <div class="form-group">
                @Html.LabelFor(model => mod.Address, htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">

                    @Html.TextAreaFor(model => mod.Address, new { @class = "form-control ", @rows = 5, @cols = 20, @id = "editor1" })


                    @Html.ValidationMessageFor(model => mod.Address, "آدرس الزامی میباشد", new { @class = "text-danger" })

                </div>
            </div>
            <div class="form-group">

                @Html.LabelFor(model => mod.recive_date, htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.EditorFor(model => mod.recive_date, null, "recive_date", new { htmlAttributes = new { @class = "form-control", @id = "PersianDate" } })
                    @Html.ValidationMessageFor(model => mod.recive_date, "تاریخ معتبر نمیباشد!", new { @class = "field-validation-error " })

                </div>
            </div>

            <div class="form-check">
                @Html.LabelFor(model => mod.OfflineOrder, htmlAttributes: new { @class = "control-label col-md-2" })
                @Html.EditorFor(model => mod.OfflineOrder, null, "OfflineOrder", new { htmlAttributes = new { @class = "form-check-input" } })
                @Html.ValidationMessageFor(model => mod.OfflineOrder, "", new { @class = "field-validation-error " })

            </div>
            <div class="form-row">
                <div class="col col-md-offset-2">
                    <input type="submit" value="پرداخت" class="btn btn-success" />
                    @*<a class="btn btn-default" href="/Order/BookPayment/"> <i class="fas fa-shopping-cart"></i>  سفارش آفلاین </a>*@


                </div>
            </div>

        }
    </div>

</div>

@section Scripts {

    @Scripts.Render("~/bundles/jqueryval")
}

当我使用表单时,它会导致无法将我的字段名称绑定到模型,我无法弄清楚为什么它只是无法识别地址字段而其他字段没有问题。

【问题讨论】:

  • 在您看来,您是否包含了模型?如果是这样,您可以使用asp-for。或者您在提交后调用的任何操作都可以使用name 获取该地址参数
  • 我做了@iamaaarianme,但它只是没有正确呈现地址字段,不知道为什么。
  • 为什么你写得像'model => mod.Address'而不是'model => Model.Address',仍然没有正确显示然后添加你的htmlattribute“Html.TextAreaFor(model => mod.Address, new { class= "form-control ", rows = 5, cols = 20, id = "editor1", Name = "editor1" })" 请注意在每个属性中添加'@',在你写的时候,在这里的评论部分不允许有多个@符号
  • @Ajay2707 mod 指的是 Mode[0]

标签: c# asp.net asp.net-mvc


【解决方案1】:

您需要使用Html.TextArea(或手动写出)而不是Html.TextAreaFor

你需要检查control和controlFor之间的区别(见下文)

“最终它们都生成相同的 HTML,但 Html.TextBoxFor() 是强类型的,而 Html.TextBox 不是。

一般两件事:

  1. 键入的 TextBoxFor 将为您生成输入名称。这通常只是属性名称,但对于复杂类型的属性可以包含下划线,例如“customer_name”
  2. 使用键入的 TextBoxFor 版本将允许您使用编译时检查。因此,如果您更改模型,则可以检查视图中是否有任何错误。”

请参考:

Html.Textbox VS Html.TextboxFor

difference between Html.TextBox and Html.TextBoxFor

ASP.NET MVC 4 override emitted html name and id

【讨论】:

    【解决方案2】:

    你试试这个,它会工作的

    @Html.TextArea("Address",mod.Address, new { @class = "form-control ", @rows = 5, @cols = 20, @id = "editor1" })
    

    【讨论】:

    • 我也知道我可以使用new { @class = "form-control ", @rows = 5, @cols = 20, @id = "editor1",Name="recive_address" },但我想知道问题
    • @AmirKian 模型绑定问题。您不是绑定从动作传递的模型,而是绑定从模型中的动作接收到的列表的第一个元素。第二个原因,您似乎在此字段上使用了一些编辑器,所以可能就是这个原因。
    猜你喜欢
    • 2019-10-21
    • 1970-01-01
    • 2015-10-26
    • 1970-01-01
    • 1970-01-01
    • 2021-12-04
    • 1970-01-01
    • 1970-01-01
    • 2016-11-28
    相关资源
    最近更新 更多