【问题标题】:editor template return null value编辑器模板返回空值
【发布时间】:2014-12-14 23:18:25
【问题描述】:

我根据这篇文章ASP.NET MVC: Annotated for Input by Dino Esposito创建了一个编辑器模板

在我按下提交按钮之前一切正常。我发现我的 POST 函数返回模型为 NULL,就像模型没有绑定到视图一样。我一直在尝试我从互联网上找到的所有我知道的技巧,但我仍然无法修复它。

这是我的控制器

    // GET: /Asset/New

    public ActionResult New()
    {
        ViewBag.typeID = new SelectList(db.Ref_Asset_Types, "ID", "name");
        return View(new AssetViewModel());
    }

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult New(AssetViewModel vm) 
    // vm.asset should contain new value but currently return null
    {
        if (ModelState.IsValid)
        {
            db.Assets.Add(vm.asset);
            db.SaveChanges();
            return RedirectToAction("Index");
        }
        ViewBag.typeID = new SelectList(db.Ref_Asset_Types, "ID", "name", vm.asset.typeID);         
        return View("New", vm);
    }

这是我的看法

    @using (Html.BeginForm("New","Asset","POST")) {
      @Html.AntiForgeryToken()
      @Html.ValidationSummary(true)

      @Html.EditorFor(m=>m.asset, "InputTemplate" ) 

// 注意:如果我不使用自己的模板,则代码有效 ==> @Html.EditorFor(m=>m.asset)

      <div class="form-actions btn pull-right">
         @Html.ActionLink("Back to List", "Index", null, new { @class = "btn btn-sm"})
        <button type="reset" class="btn btn-sm" value="Index"> 
            Reset 
        </button>
        <button type="submit" class="btn btn-sm btn-success">
            <i class="glyphicon glyphicon-plus"></i>
            Tambah
        </button>          
      </div>
    }

这是我的输入模板

    @inherits System.Web.Mvc.WebViewPage 
    @if (Model == null) 
    { 
       <span>@ViewData.ModelMetadata.NullDisplayText</span> 
    } 
    else 
    {        
       foreach (var prop in ViewData 
          .ModelMetadata 
          .Properties 
          .Where(pm => pm.ShowForDisplay && !ViewData.TemplateInfo.Visited(pm))) 
       { 
          if (prop.DisplayName != null) {   // only display prop not of ComplexType
          // note : using bootstrap for css styling
          <div class="form-group col-xs-6">
            <label class="col-xs-4 control-label text-right">
               <span style="color:red"> @(prop.IsRequired ? "*" : "")  </span>
               <span>@prop.GetDisplayName()</span>
            </label>

          <div class="col-xs-8">                      
            @if(prop.IsReadOnly) 
            { 
               <span class="readonly-field">@Html.Display(prop.PropertyName)</span> 
            } 
            else if (prop.TemplateHint == "DropDown")
            { 
               <span>@Html.DropDownList(prop.PropertyName,(IEnumerable<SelectListItem>) ViewData[prop.PropertyName], new { @class = "form-control" })</span>
               <span>@Html.ValidationMessage(prop.PropertyName)</span>
            } 
            else
            {
               <div class="editor-field"> 
                 <span>@Html.Editor(prop.PropertyName, new { @class = "text-box single-line form-control" })</span> 
                 <span>@Html.ValidationMessage(prop.PropertyName, new { @class = "label-danger" } )</span> 
               </div>
            }                     
          </div>
         </div>

         } // if
       } // foreach
    }

这是我的视图模型

    using System;
    using SIGMA.Models;

    namespace SIGMA.ViewModels
    {

    public class AssetViewModel
    { 
       public AssetViewModel() 
       {
          asset = new Asset();
       }
       public Asset asset { get; set; }
    }   


    }

这是我的模特

    public class Asset
    {
      [Key]
      [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
      [HiddenInput(DisplayValue = false)]
      public int ID { get; set; }

      [DisplayName("No. Siri")]
      [StringLength(45)]
      public string serial_num { get; set; }

      [DisplayName("Model")]
      [Required(ErrorMessage = "Model perlu diisi!")]
      [StringLength(45)]
      public string model { get; set; }

      [DisplayName("Harga Seunit")]
      [RegularExpression(@"^\d{0,6}(\.\d{2})?$", ErrorMessage = "Sila gunakan format harga yang betul.")]
      public float? unit_cost { get; set; }

      [UIHint("DropDown")]
      [DisplayName("Jenis Aset")]
      [Required(ErrorMessage = "Jenis aset perlu dipilih!")]
      [DisplayFormat(NullDisplayText = "Belum didaftar")]
      public int? typeID { get; set; }

      public virtual Ref_Asset_Type type { get; set; }
    }

【问题讨论】:

  • 查看源代码时,编辑器模板生成的输出是什么样的?粗略一看,我建议反射的属性名称与模型绑定约定不匹配
  • 您的 EditorTemplate 正在为属性 asset 提供控件。您尚未显示此类,但假设它是 typeof Asset 并包含属性 ID,则关联的控件将具有 name="ID",但您的 POST 方法参数是 AssetViewModel,这意味着控件必须是 name="asset.ID"。您想使用标准 EditorTemplate 无法完成的代码来实现什么目标?
  • @Stephen Muecke - 我在这里尝试创建一个可供任何模型使用的模板。所以我可以在所有添加和编辑视图中保持相同的样式。顺便说一句,我尝试发送模型而不是视图模型,但我无法将模型传递给我的模板。 (此视图模型遵循 Dino 文章的建议)
  • 我已添加视图模型和模型以供参考。 @Brent Mannering - 在我看来,来源实际上与我使用默认模板时相同 => 输入框将具有 id = assets_property_name 和 name = property_name
  • @bapak71,这是真正的代码吗(如果它只包含一个属性即域模型,为什么还要有一个视图模型)?检查正在生成的 html - 控件上的 name 属性是 name="asset.ID" 还是 name="ID"

标签: asp.net asp.net-mvc


【解决方案1】:

抱歉,麻烦各位了。我想我解决了。

我最大的错误是使用保留字“模型”和“类型”作为我的属性名称。这在使用用户定义编辑器模板解释我的模型时如何导致 asp.net 出现问题。

一旦我将我的属性名称 - 模型更改为模型名称并将类型更改为资产类型,我就可以在我的返回模型中看到我的条目了。

谢谢大家

....为这个愚蠢的错误花了一整天的时间,但吸取的教训是值得的

【讨论】:

    猜你喜欢
    • 2011-08-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多