在不使用Html.EditorFor()asp.net mvc的情况下创建模型引用时出现问题

时间:2014-08-28 13:36:12

标签: c# asp.net-mvc

我在尝试创建模型限制的引用时面临一个问题:

    public int RestrictionID
    public string portefeuille
    public int AssetID
    public int SegmentID
    public int SubAssetID
    public int Min
    public int Max
    public string logic_op
    public virtual Asset Asset
    public virtual Segment Segment
    public virtual SubAsset SubAsset

这不是在创建视图中使用普通模板,而是使用@ Html.EditorFor我使用一个带有脚本的下拉列表来填充下拉列表,具体取决于之前选择的项目,但是在提交时什么都没发生没有错误没有重定向,当然引用也没有添加到数据库中。 这是我的创建视图:

  <div class="editor-label">
        @Html.LabelFor(model => model.portefeuille)
    </div>
    <div class="editor-field">
        @Html.EditorFor(model => model.portefeuille)
        @Html.ValidationMessageFor(model => model.portefeuille)
    </div>

    @Html.DropDownList("Asset", ViewBag.AssetID as SelectList, "Select a Asset Class", new { id="Asset" })<br />
            <select id="Segment" name="segment"></select><br />   //Here I am not using Html.EditorFor as EF does
            <select id="subAsset" name="SubAsset"></select><br />

    <div class="editor-label">
        @Html.LabelFor(model => model.Min)
    </div>
    <div class="editor-field">
        @Html.EditorFor(model => model.Min)
        @Html.ValidationMessageFor(model => model.Min)
    </div>

    <div class="editor-label">
        @Html.LabelFor(model => model.Max)
    </div>
    <div class="editor-field">
        @Html.EditorFor(model => model.Max)
        @Html.ValidationMessageFor(model => model.Max)
    </div>

    <div class="editor-label">
        @Html.LabelFor(model => model.logic_op)
    </div>
    <div class="editor-field">
        @Html.EditorFor(model => model.logic_op)
        @Html.ValidationMessageFor(model => model.logic_op)
    </div>

和我的RestrictionController :(我省略了无用的部分)

    public ActionResult Create()
    {
        ViewBag.AssetID = new SelectList(db.Assets, "AssetID", "Asset_Name");

        return View();
    }

    //
    // POST: /Restriction/Create

    [HttpPost]
    public ActionResult Create(Restriction restriction)
    {
        if (ModelState.IsValid)
        {
            db.Restrictions.Add(restriction);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        ViewBag.AssetID = new SelectList(db.Assets, "AssetID", "Asset_Name", restriction.AssetID);

        return View(restriction);
    }

有人可以帮忙找出问题所在吗?

感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

模型a中属性的名称应该与html中元素的名称相同,以便在回发后绑定值。这就是下面代码的原因

 <select id="Segment" name="segment"></select><br />   //Here I am not using Html.EditorFor as EF does
            <select id="subAsset" name="SubAsset"></select><br />

应替换为。

 <select id="Segment" name="SegmentID"></select><br />   //Here I am not using Html.EditorFor as EF does
            <select id="subAsset" name="SubAssetID"></select><br />

始终关注任何技术生成的HTML。这将有助于您了解事情的运作方式。