【问题标题】:Why is this button not submitting my form? ASP.NET MVC为什么这个按钮没有提交我的表单? ASP.NET MVC
【发布时间】:2020-07-27 03:42:17
【问题描述】:

我有一个模式,在单击按钮“submitBtn”(包含在表单中)时会提示,我的模式中的一个按钮 (btnSubmit) 应该使用 javascript 代码提交表单。但是,它没有这样做并引发错误;

" Uncaught TypeError: Cannot read property 'submit' of null at HTMLButtonElement. (Category:72)strong text "

我不确定它为什么这样做?警报按预期运行..

下面是我的表单,下面是我的脚本标签,其中包含必要的 javascript 代码。任何帮助将不胜感激,谢谢 :)

表单 HTML:(链接到“CategoryController”)

@using (Html.BeginForm("Category", "Category", FormMethod.Post))
{

    <form id="formField">

        <label id="CategoryDescriptionLabel">Description</label>

        <input id="CategoryDescription" type="text" name="categoryDescription" /> 

        <input type="button" value="submit" id="submitBtn" data-toggle="modal" data-target="#confirm-submit" /> 

    </form>

}

Javascript:

<script>

    document.getElementById("btnSubmit").addEventListener("click", function () {
        alert("Submitting!");
        document.getElementById("formField").submit()
    });

</script>

注意:两个代码 sn-ps 都在 cshtml 文件中..

【问题讨论】:

    标签: javascript html asp.net asp.net-mvc model-view-controller


    【解决方案1】:

    您实际上定义了 2 个嵌套形式:第一个使用 Html.BeginForm()(这已经包含了 &lt;form&gt;&lt;/form&gt; 之间的所有内容)然后 另一个 em> 手动使用&lt;form&gt;&lt;/form&gt; 标签。

    在 HTML 中嵌套表单是非法的。手动创建的&lt;form&gt;最好省略掉,改成这样:

    @using (Html.BeginForm("Category", "Category", FormMethod.Post))
    {
        <label id="CategoryDescriptionLabel">Description</label>
    
        <input id="CategoryDescription" type="text" name="categoryDescription" /> 
    
        <input type="button" value="submit" id="submitBtn" data-toggle="modal" data-target="#confirm-submit" /> 
    }
    

    要为生成的&lt;form&gt; 定义一个id,您可以使用这个:

    @using (Html.BeginForm("Category", "Category", FormMethod.Post, new { id = "bla" }))
    {
        ...
    }
    

    【讨论】:

    • 哦,好吧,我明白你的意思了,我将如何在我的 javascript 中引用 Html.BeginForm()?是否可以为该表单分配 ID?
    猜你喜欢
    • 1970-01-01
    • 2018-12-23
    • 1970-01-01
    • 1970-01-01
    • 2020-04-09
    • 1970-01-01
    • 2014-04-08
    相关资源
    最近更新 更多