Razor RenderPartial生成错误的HTML

时间:2018-05-31 09:09:49

标签: razor asp.net-core

我有一个页面项目编辑,其中包含多个部分渲染表单,用于删除图像。项目编辑页面:

@model EditModel
<form method="post" enctype="multipart/form-data">
    <input asp-for="ItemModel.Id" type="hidden" />
    <input asp-for="ItemModel.AllOtherFields" type="hidden" />
</form>
@if (Model.ItemModel.ImageViewModels != null && Model.ItemModel.ImageViewModels.Any())
{
    foreach(var imageViewModel in Model.ItemModel.ImageViewModels)
    {
       Html.RenderPartial("ItemImage/_itemImageEdit", imageViewModel);
    }
}

ItemImage / _itemImageEdit

@model ViewModels.ItemImageViewModel

<form asp-controller="Images" asp-action="Delete" method="post">
    <input type="hidden" asp-for="@Model.Id" />
    <img src="@Url.Action("Get", "Images", new { id = Model.Id })" />
    <input type="submit" value="Delete" />
</form>

这是我最奇怪的最终HTML

<form method="post" action="/Images/Delete/5" novalidate="novalidate">
     <input type="hidden" data-val="true" data-val-required="The Id field is required." id="Id" name="Id" value="5">
     <img src="/Images/Get/10">
    <input type="submit" value="Delete">
</form>

其中5-项目ID和10 - 图像ID。所以这是预期和正确的

<img src="/Images/Get/10">

虽然不是这样。项目ID使用而不是id(ItemImageViewModel.id)

action="/Images/Delete/5"

我不知道为什么@Model.Id会在同一个子视图上生成不同的ID。

EDIT1:

public class ItemImageViewModel
{
    [BindProperty]
    public int Id { get; set; }
    public string Title { get; set; }
    public int ItemId { get; set; }

}

public class ItemViewModel
{
    public ItemViewModel()
    {
    }
    public ItemViewModel(ItemViewModel vm)
    {
        Id = vm.Id;
        Title = vm.Title;
        ImageViewModels = vm.ImageViewModels;
    }
    public int Id { get; set; }
    public string Title { get; set; }
    public IEnumerable<ItemImageViewModel> ImageViewModels { get; set; }
}

我删除了不相关的字段。 调试器显示没问题 Debugger shows alright

1 个答案:

答案 0 :(得分:0)

现在,这段奇怪的代码生成了它应该生成的内容

<form action="@Url.Action("Delete", "Images", new { id = Model.Id })" method="post">
    <input type="hidden" id="Id" name="Id" value="@Html.DisplayFor(m => Model.Id)" />
    @Html.HiddenFor(m => Model.ItemId)"
    <img src="@Url.Action("Get", "Images", new { id = Model.Id })" />
    <input type="text" asp-for="@Model.Title" />
    <input type="submit" value="Delete" />
</form>


<form action="/Images/Delete/10" method="post" novalidate="novalidate">
    <input type="hidden" id="Id" name="Id" value="10">
    <input data-val="true" data-val-required="The ItemId field is required." id="ItemId" name="ItemId" type="hidden" value="5">"
    <img src="/Images/Get/10">
    <input type="text" id="Title" name="Title" value="Jacket">
    <input type="submit" value="Delete">
</form>

what received