我希望有人可以帮助我解决我遇到的这个简单问题,但无法弄清楚。
我在 javascript 中使用 Ajax 调用来提交我的表单,这没问题。
我现在正在尝试使用 html.beginform 帮助程序,但它没有在我用于 Ajax 调用的同一个控制器内点击 post 方法。
为了使 post 方法被击中,我需要做什么?
这是我的控制器代码:
[HttpPost]
//[ValidateAntiForgeryToken]
public async Task<ActionResult> Create(Category category)
{
if (ModelState.IsValid)
{
try
{
await db.AddCategoryAsync(category);
}
catch (System.Exception ex)
{
throw ex;
}
}
return View(category);
}
这是我的html:
@using (Html.BeginForm())
{
@*@Html.AntiForgeryToken()*@
@Html.ValidationSummary()
<div class="body-content">
<h4>Category</h4>
<hr />
<div class="form-group">
<div class="col-offset-1 col-lg-11 col-md-11 col-sm-11 col-xs-11">
@Html.EditorFor(model => model.Description, new { htmlAttributes = new { @class = "form-control", @placeholder = "Description" } })
@Html.ValidationMessageFor(model => model.Description, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
<button type="submit" id="btnCategoryCreate" class="btn btn-primary col-offset-2"><span class="glyphicon glyphicon-save"></span> Create</button>
</div>
</div>
}
这是我单击提交按钮时浏览器中的 url。它在我的Home Controller 中执行Create方法,但在调试期间,Controller 方法永远不会受到影响。
有人请帮助,让我知道我忽略了什么简单的错误......
http://localhost:1681/Home/Create?Description=Medical
编辑
表单标签的值 OK.. 问题是.. 在表单操作标签上显示:“看到一个‘表单’开始标签,但已经有一个活动的‘表单’元素。不允许嵌套表单。忽略此标签( )。
这就是它不发布的原因。
我删除了 _Layout.cshtml 文件中的表单标签,现在它正在发布,因为这个特定页面现在只有一个表单标签,而当我通过 Ajax 使用所有调用时,我的 _Layout.cshtml 文件中有表单标签.
但是,当我使用一种表单进行 Ajax 调用时,我的按钮位于文本框的右侧,而不是位于其下方:
<form id="form1" class="form-horizontal" role="form">
我尝试将以下内容放在 @html.BeginForm 标记上,但按钮仍在右侧。
@using (Html.BeginForm("Create", "Home", FormMethod.Post, new { htmlAttributes = new { @class="form-horizontal", role="form"}}))
我现在如何在输入框下方获取我的按钮?
@using (Html.BeginForm("Create", "Home", FormMethod.Post, new { htmlAttributes = new { @class="form-horizontal", role="form"}}))
{
@*@Html.AntiForgeryToken()*@
@Html.ValidationSummary()
<div class="body-content">
<h4>Category</h4>
<hr />
<div class="form-group">
<div class="col-offset-1 col-lg-11 col-md-11 col-sm-11 col-xs-11">
@Html.EditorFor(model => model.Description, new { htmlAttributes = new { @class = "form-control", @placeholder = "Description" } })
@Html.ValidationMessageFor(model => model.Description, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
<button type="submit" id="btnCategoryCreate" class="btn btn-primary col-offset-2"><span class="glyphicon glyphicon-save"></span> Create</button>
</div>
</div>
}