简体   繁体   English

为什么这个按钮不提交我的表单? ASP.NET MVC

[英]Why is this button not submitting my form? ASP.NET MVC

I have a modal that is prompted upon clicking the button 'submitBtn' (contained within the form), the one button in my modal (btnSubmit) should submit the form using javascript code.我有一个模式,在单击按钮“submitBtn”(包含在表单中)时会提示,我的模式(btnSubmit)中的一个按钮应该使用 javascript 代码提交表单。 However, it fails to do so and throws an error;但是,它没有这样做并抛出错误;

" Uncaught TypeError: Cannot read property 'submit' of null at HTMLButtonElement. (Category:72) strong text " “未捕获的类型错误:无法在 HTMLButtonElement 读取 null 的属性‘提交’。(类别:72)强文本

i am unsure as to why its doing this?我不确定为什么要这样做? The alert runs as intended..警报按预期运行。

Below is my form, and below that is my script tag housing the necessary javascript code.. Any help would be greatly appreciated, thank you:)下面是我的表格,下面是我的脚本标签,其中包含必要的 javascript 代码。非常感谢任何帮助,谢谢:)

Form HTML: (LINKED TO 'CategoryController')表格 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: Javascript:

<script>

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

</script>

NB: Both code snippets are within the cshtml file..注意:两个代码片段都在 cshtml 文件中。

You have in fact defined 2 nested forms : first one using Html.BeginForm() (this already wraps whatever is inside it between <form> and </form> ) and then another one manually by using <form> and </form> tags.您实际上已经定义了2 个嵌套的 forms :第一个使用Html.BeginForm() (这已经包装了<form></form>之间的任何内容),然后使用<form></form>手动定义了另一个标签。

Having nested forms is illegal in HTML. It is best to leave out the manually created <form> , change it to this:在HTML中嵌套了forms是不合法的,手工创建的<form>最好去掉,改成这样:

@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" /> 
}

To define an id for the generated <form> , you can use this:要为生成的<form>定义一个id ,你可以使用这个:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM