部分视图 - 避免嵌套表单

时间:2013-10-21 14:44:20

标签: asp.net-mvc razor partial-views

查看

@using (Html.BeginForm())
{
    ...form elements
    @Html.Action("PartialView")
}

PartialView

if (something) {
    <input type="submit" value="Submit" />
} else {
    @using (Html.BeginForm())
    {
        <input type="submit" value="Submit" />
    }

有人可以提出解决上述问题的方法吗?

如果PartialView if语句返回false,我最终会使用嵌套表单。我可以在局部视图中移动窗体关闭括号,以避免嵌套窗体和页面呈现正确但这会扰乱visual studio,因为它希望在视图中看到近括号。那有关系吗?

编辑:

根据Chris的评论,以下修改是一种更好的方法吗?即一个表单有两个提交按钮,在同一个操作方法中调用不同的代码?

PartialView

if (something) {
    <input type="submit" name="btn" value="Submit1" />
} else {
    <input type="submit" name="btn" value="Submit2" />
}

控制器

[HttpPost]
public ActionResult Index()
{
    if (btn == "Submit1") {
        ...do a thing
    } else {
        ...do another thing
    };
}

2 个答案:

答案 0 :(得分:0)

另一个<form>内的

<form>标记不是有效的HTML

参考W3c Spec

可用的解决方法

http://blog.avirtualhome.com/how-to-create-nested-forms/

答案 1 :(得分:0)

我遇到了同样的问题,并想出了一个真正解决它的助手。

/**
 * Ensure consequent calls to Html.BeginForm are ignored. This is particularly useful
 * on reusable nested components where both a parent and a child begin a form.
 * When nested, the child form shouldn't be printed.
 */
public static class SingleFormExtensions
{
    public static IDisposable BeginSingleForm(this HtmlHelper html)
    {
        return new SingleForm(html);
    }

    public class SingleForm: IDisposable
    {
        // The form, if it was needed
        private MvcForm _form;

        public SingleForm(HtmlHelper html)
        {
            // single per http request
            if (!HttpContext.Current.Items.Contains(typeof(SingleForm).FullName))
            {
                _form = html.BeginForm();
                HttpContext.Current.Items[typeof(SingleForm).FullName] = true; // we need the key added, value is a dummy
            }
        }

        public void Dispose()
        {
            // close the form if it was opened
            if (_form != null)
            {
                _form.EndForm();
                HttpContext.Current.Items.Remove(typeof(SingleForm).FullName);
            }
        }
    }
}

要使用它,请包含扩展程序的命名空间,并在任何位置执行@Html.BeginSingleForm(。不仅在嵌套视图中,而且在父视图中。

兴趣点:需要保存表单是否已提前打开。我们不能有每个线程变量ThreadStatic的静态或静态,因为许多Asp.Net线程可能会使用它。添加变量的唯一单线程和每个http请求位置是HttpContext.Current.Items字典。

提交按钮的数量没有限制。问题是嵌套的form元素。要避免使用多个提交按钮,您可以使用jquery隐藏它们,或者扩展此帮助程序以在结尾处自动添加提交按钮。

相关问题