【问题标题】:Combine multiple properties in @html.Editorfor Razor在@html.Editorfor Razor 中组合多个属性
【发布时间】:2015-10-14 22:15:47
【问题描述】:

我们必须在 Razor 视图中将多个属性组合到一个 EditorFor 字段中。

我们有属性 Quantity、UnitOfMeasure 和 Ingredient。这些需要结合起来,这样用户就可以只输入他或她需要的东西,即 10 公斤土豆,而不是在多个字段中输入信息。

完成后,我们还需要对 UOM 和成分属性进行自动填充。

我为此代码创建了一个局部视图。

@model IEnumerable<RecipeApplication.Models.RecipeLine>
<div class="form-group">
    @Html.Label("Ingrediënten", htmlAttributes: new { @class = "control-label col-md-2" })
    <div>
        @foreach (var item in Model)
        {

            <p>
                @Html.EditorFor(modelItem => item.Quantity, new { htmlAttributes = new { @class = "form-control-inline" } })
                @Html.EditorFor(modelItem => item.UnitOfMeasure.Abbreviation, new { htmlAttributes = new { @class = "form-control-inline" } })
                @Html.EditorFor(modelItem => item.Ingredient.Name, new { htmlAttributes = new { @class = "form-control-inline" } })
            </p>

        }
    </div>

</div>

显然这不是本意。

这是编辑功能的代码:

    public ActionResult Edit(int? id)
    {
        if (id == null)
        {
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }
        RecipeModel recipeModel = db.Recipes.Find(id);
        if (recipeModel == null)
        {
            return HttpNotFound();
        }

        GetRecipeLines(id);

        return View(recipeModel);
    }

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Edit([Bind(Include = "Name,Description,ImageUrl")] RecipeModel recipeModel, int?id)
    {
        if (ModelState.IsValid)
        {
            db.Entry(recipeModel).State = EntityState.Modified;
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        GetRecipeLines(id);

        return View(recipeModel);
    }

我查看了 Google 和 StackOverflow,但找不到正确的答案来完成这项工作。

就我个人而言,此刻我什至不知道从哪里开始。

我希望有人可以帮助解决这个问题。

谢谢。

【问题讨论】:

  • 向您的模型添加一个字符串字段,该字段接受输入并在您的控制器中对其进行解析。在一个字符串中输入多个模型值没有标准控件。
  • @D Stanley 我会使用自定义模型绑定器来完成类似的事情,而不是向模型中添加一个字段,该字段只是为了解析而存在,在绑定器中获取它,在那里解析它,然后按照预期填充模型。

标签: c# asp.net-mvc asp.net-mvc-4 razor properties


【解决方案1】:

在 ReceipLine 上添加一个新的 getter 属性

C# 6.0 语法:

public string QuantityUomIngredient =>
$"{Quantity} {UnitOfMeasure?.Abbreviation ?? ""} {Ingredient?.Name ?? ""}";

那么你的视图应该是这样的

@Html.EditorFor(modelItem => item.QuantityUomIngredient ...

然后构建一个自定义模型绑定器,将 QuantityUomIngredient 解析为其对应的属性(这部分实现起来应该很有趣)。但请务必对输入进行良好的验证,以便您有良好的数据可以解析。

【讨论】:

  • 好答案!我不知道那个 getter 在做什么,但是自定义模型绑定器肯定是这里的关键
  • 如果你有 VS 2015,那就太棒了!看看:github.com/dotnet/roslyn/wiki/New-Language-Features-in-C%23-6
  • 这听起来很不错@LeoNix。我会开始工作,一旦我开始工作,我就会把它发回来。
【解决方案2】:

感谢 Leo Nix 的回答,它肯定让我朝着正确的方向前进。

这是我到目前为止编写的代码,它看起来就像一个魅力。 (我还没有包含错误处理。)

public class RecipeLine
{
    [Key]
    public int RecipeLineId { get; set; }
    public int RecipeId { get; set; }
    public double Quantity { get; set; }
    public virtual UnitOfMeasureModel UnitOfMeasure { get; set; }
    public virtual IngredientModel Ingredient { get; set; }
    public string QuantityUomIngredient => $"{Quantity} {UnitOfMeasure?.Abbreviation ?? ""} {Ingredient?.Name ?? ""}";
}

还有我写的自定义活页夹。这需要相当多的额外研究。

 class RecipeLineCustomBinder : DefaultModelBinder
    {
        private RecipeApplicationDb db = new RecipeApplicationDb();

        public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            HttpRequestBase request = controllerContext.HttpContext.Request;

            // Get the QuantityCustomIngredient from the webform. 
            string quantityUomIngredient = request.Form.Get("QuantityUomIngredient");
            // Get the IngredientID from the webform.
            int recipeID = int.Parse(request.Form.Get("RecipeId"));
            // Split the QuantityCustomIngredient into seperate strings. 
            string[] quantityUomIngredientArray = quantityUomIngredient.Split();
            //string[] quantityUomIngredientArray = quantityUomIngredient.Split(new string[] { " " }, 2, StringSplitOptions.RemoveEmptyEntries);

            if (quantityUomIngredientArray.Length >= 3)
            {
                // Get the quantity value
                double quantityValue;
                bool quantity = double.TryParse(quantityUomIngredientArray[0], out quantityValue);

                // Get the UOM value. 
                string uom = quantityUomIngredientArray[1];
                UnitOfMeasureModel unitOfMeasure = null;
                bool checkUOM = (from x in db.UnitOfMeasures
                                 where x.Abbreviation == uom
                                 select x).Count() > 0;
                if (checkUOM)
                {
                    unitOfMeasure = (from x in db.UnitOfMeasures
                                     where x.Abbreviation == uom
                                     select x).FirstOrDefault();
                }

                // Get the ingredient out of the array.
                string ingredient = "";
                for (int i = 2; i < quantityUomIngredientArray.Length; i++)
                {
                    ingredient += quantityUomIngredientArray[i];
                    if (i != quantityUomIngredientArray.Length - 1)
                    {
                        ingredient += " ";
                    }
                }

                bool checkIngredient = (from x in db.Ingredients where x.Name == ingredient select x).Count() > 0;
                IngredientModel Ingredient = null;
                if (checkIngredient)
                {
                    Ingredient = (from x in db.Ingredients
                                  where x.Name == ingredient
                                  select x).FirstOrDefault();
                }

                // Return the values. 
                return new RecipeLine
                {
                    Quantity = quantityValue,
                    UnitOfMeasure = unitOfMeasure,
                    Ingredient = Ingredient,
                    RecipeId = recipeID
            };
            }
            else
            {
                return null;
            }

        }
    }

在 Razor 视图中,这是我使用的代码:

    <div class="form-group">
        @Html.LabelFor(model => model.QuantityUomIngredient, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.QuantityUomIngredient, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.QuantityUomIngredient, "", new { @class = "text-danger" })
        </div>
    </div>

我在 Global.asax.cs 中添加了自定义活页夹

public class MvcApplication : System.Web.HttpApplication
{
    protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();
        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
        RouteConfig.RegisterRoutes(RouteTable.Routes);
        BundleConfig.RegisterBundles(BundleTable.Bundles);
        ModelBinders.Binders.Add(typeof(RecipeLine), new RecipeLineCustomBinder());
    }
}

最后将自定义绑定器添加到控制器中

    [HttpPost]
    public ActionResult Create([ModelBinder(typeof(RecipeLineCustomBinder))] RecipeLine recipeLine)
    {
        if (ModelState.IsValid)
        {
            db.RecipeLines.Add(recipeLine);
            db.SaveChanges();
            return RedirectToAction("Index", new { id = recipeLine.RecipeId });
        }
        return View(recipeLine);
    }

我希望这也能帮助其他开发者。

【讨论】:

    猜你喜欢
    • 2013-05-26
    • 2012-01-23
    • 1970-01-01
    • 1970-01-01
    • 2019-07-14
    • 1970-01-01
    • 1970-01-01
    • 2019-03-25
    • 2021-10-18
    相关资源
    最近更新 更多