【问题标题】:Adding fields to a form using ajax使用ajax向表单添加字段
【发布时间】:2013-06-02 18:36:51
【问题描述】:

我正在使用 ajax 动态地将项目添加到字段列表中。

问题是这些项目没有正确的 ID 或名称,因此它们无法正确映射,并且在提交表单时不会反映在模型中。

这是我的代码结构:

public class Main
{
    public IEnumerable<FieldSection> Sections { get; set; }
}

public class FieldSection
{
    public virtual IList<Field> Fields { get; set; }
}

public class Field
{
    [Required]
    public string Value { get; set; }
}

这就是我渲染 Main 的方式:

<div class="field-sections">
    <div id="sections">
        @Html.EditorFor(model => model.Sections)
    </div>
    <p>
        <span class="add-section">Add Section</span>
    </p>
</div>

一个 Section 有一个这样的 EditorTemplate:

<div class="field-list">
    @Html.EditorFor(model => model.Fields)
</div>
<p>
    <span class="add-field">Add Field</span>
</p>

一个字段有一个像这样的 EditorTemplate:

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

如果我有一个部分和两个字段,则 Value 字段的最后一个文本框的 ID 为 Sections_0__Fields_1__Value,名称为 Sections[0].Fields[1].Value

我通过渲染我的 EditorTemplate Field.cshtml,通过 ajax 添加 Field,将其返回到页面并将其添加到部分。但是 ID 为 Value,名称为 Value

这显然是不正确的。似乎我可以在使用 javascript 将其添加到页面之前修改我的 HTML 以为其提供正确的 ID/名称,但这是一个非常糟糕的解决方案。如何让我的视图以正确的名称和 ID 呈现?还是我以错误的方式处理这个问题?

编辑

渲染域代码:

[HttpGet]
public string Field()
{
    return MvcRenderUtility.RenderToString(this, "EditorTemplates/TemplateField", new TemplateField());
}

还有渲染工具:

public static class MvcRenderUtility
{
    public static string RenderToString(Controller controller, string viewName, object model)
    {
        if (string.IsNullOrEmpty(viewName))
            viewName = controller.ControllerContext.RouteData.GetRequiredString("action");

        controller.ViewData.Model = model;

        using (StringWriter sw = new StringWriter())
        {
            ViewEngineResult viewResult = ViewEngines.Engines.FindPartialView(controller.ControllerContext, viewName);
            ViewContext viewContext = new ViewContext(controller.ControllerContext, viewResult.View, controller.ViewData, controller.TempData, sw);
            viewResult.View.Render(viewContext, sw);
            return sw.GetStringBuilder().ToString();
        }
    }
}

【问题讨论】:

  • 我正在通过渲染我的 EditorTemplate Field.cshtml 通过 ajax 添加一个字段,将其返回到页面并将其添加到部分。但是 ID 是 Value,名称是 Value。 - 代码在哪里?
  • 在上面为你添加了,谢谢。

标签: .net ajax asp.net-mvc asp.net-mvc-4 razor-2


【解决方案1】:

我建议你在浏览器中添加字段,也许使用 jQuery,并在 post 操作方法中检索新字段的值:

public ActionResult Edit(MyModel model, FormCollection raw) {

  // scan the raw collection for new fields and add them to your model

}

【讨论】:

  • 如果我需要通过创建 HTML 服务器端(以获取验证等)来添加我的字段,通过 AJAX 加载,我将如何使名称不同?否则,它们会返回相同的值,并且验证一个字段会验证所有新添加的字段..
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-04-18
  • 1970-01-01
  • 1970-01-01
  • 2013-08-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多