我希望有人能帮我解决这个简单的问题,但我无法解决。
我使用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控制器中执行Create方法,但在调试过程中,控制器方法从未被命中。
有人请帮助我,让我知道我忽略了什么简单的错误。。。
http://localhost:1681/Home/Create?Description=Medical
编辑
Form标记的值好的…问题是。。表单动作标签上显示:"看到一个'form'开始标记,但已经有一个活动的'form'元素。不允许嵌套表单。忽略此标记()。
这就是为什么它没有发布。
我删除了_Layout.cshtml文件中的表单标记,现在它发布了,因为这个特定页面现在只有一个表单标记,而当我通过Ajax使用所有调用时,我的_Layout.chshtml中有表单标记。
然而,当我用一个表单进行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>
}
是否要调用方法Async?
尝试在HTML表单中添加更多信息:
@using (Html.BeginForm("Create", "Home", FormMethod.Post))
如果您想使用Ajax和异步,请使用:
@using (Ajax.BeginForm())