gpt4 book ai didi

c# - 使用 MVC3 创建和编辑字符串集合

转载 作者:太空宇宙 更新时间:2023-11-03 15:47:22 24 4
gpt4 key购买 nike

在理解如何使用表单创建和编辑字符串集合时遇到一些困难。我试过使用 EditorFor 但它似乎没有运气,而是将以下文本放入表单中。我正在尝试编辑集合“关键字”。

System.Collections.Generic.HashSet`1[MVCModuleStarter.Models.Module]System.Collections.Generic.HashSet`1[MVCModuleStarter.Models.Module]

这是我在 EditorFor 中使用的 Html,其中一个有效的 EditorFor 用于字符串以供引用。

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


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

这是我的 Controller 中的 Edit 方法;

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "ModuleId,ModuleTitle,ModuleLeader,ModuleDescription,ImageURL,Category,Keywords")] Module module)
{
if (ModelState.IsValid)
{
int moduleId = module.ModuleId;
repository.UpdateModule(module);
repository.Save();
return RedirectToAction("Details", new { Id = moduleId });
}
return View(module);
}

这是供引用的模型;

[Required, StringLength(20), Display(Name = "Category")]
public string Category { get; set; }

public virtual ICollection<Keyword> Keywords { get; set; }

关键字模型

    public class Keyword
{
[Key, Display(Name = "ID")]
public int KeywordId { get; set; }

[Required, StringLength(100), Display(Name = "Keyword")]
public string KeywordTerm { get; set; }

public virtual ICollection<Module> Modules { get; set; }
}
}

任何帮助都将是惊人的,这仍然是新的!谢谢!

最佳答案

您需要创建一个 EditorTemplate对于 Keyword , 例如

/Views/Shared/EditorTemplates/Keyword.cshtml (根据需要添加div、类名等)

@model Keyword
@Html.HiddenFor(m => m.KeywordId)
@Html.LabelFor(m => m.KeywordTerm)
@Html.TextBoxFor(m => m.KeywordTerm)
@Html.ValidationMessageFor(m => m.KeywordTerm)

然后在主视图

Html.EditorFor(m=> m.Keywords)

请注意,我省略了集合属性 Modules , 但如果您还想编辑它们,请添加另一个 EditorTemplate对于 Modules

或者您可以使用 for在主视图中循环。这意味着集合需要是 IList<T>

for(int i = 0; i < Model.Keywords.Count, i++)
{
@Html.HiddenFor(m => m.Keywords[i].KeywordId)
// other properties of Keyword
for (int j = 0; j < Model.Keywords[i].Modules.Count; j++)
{
@Html.TextBoxFor(m => m.Keywords[i].Modules[j].SomeProperty)
// other properties of Module
}
}

关于c# - 使用 MVC3 创建和编辑字符串集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27556818/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com