나는 몇 시간 동안 인터넷에서 쓰레기를 검색했지만 이것이 작동하지 않는 이유를 파악하지 못했습니다.
사용자가 작성하고 양식을 작성하고 해당 양식을 데이터베이스에 간단하게 저장하기를 원합니다. 아약스를 넣기 전에는 완벽하게 작동했습니다. 하지만 이제는 계속 오류가 발생합니다.Sorry, this method can't be called only from AJAX.
여기 내 코드가 있습니다.
제어 장치:
// GET: /AjaxStuff/Create
public ActionResult Contact()
{
return View();
}
// POST: /AjaxStuff/Create
[HttpPost]
public ActionResult Contact(Users usertocreate)
{
if (!Request.IsAjaxRequest())
{
Response.StatusCode = (int)System.Net.HttpStatusCode.BadRequest;
return Content("Sorry, this method can't be called only from AJAX.");
}
try
{
if (ModelState.IsValid)
{
_db.Table.Add(usertocreate);
_db.SaveChanges();
return Content("Record added successfully !");
}
else
{
StringBuilder strB = new StringBuilder(500);
foreach (ModelState modelState in ModelState.Values)
{
foreach (ModelError error in modelState.Errors)
{
strB.Append(error.ErrorMessage + ".");
}
}
Response.StatusCode = (int)System.Net.HttpStatusCode.BadRequest;
return Content(strB.ToString());
}
}
catch (Exception ee)
{
Response.StatusCode = (int)System.Net.HttpStatusCode.BadRequest;
return Content("Sorry, an error occured." + ee.Message);
}
}
전망:
@model Site01.Models.Users
@{
ViewBag.Title = "Contact";
AjaxOptions options = new AjaxOptions
{
Confirm = "Are you sure to save record?",
OnBegin = "OnBeginMethod",
OnFailure = "OnFailtureMethod",
OnSuccess = "OnSuccessMethod",
OnComplete = "OnCompleteMethod"
};
}
<script src="~/Scripts/jquery.unobtrusive-ajax.min.js"></script>
<h3>Deixe-nos uma mensagem!</h3>
<p>Duvidas ou apenas a deixar um comentário? Preencha o formulário!</p>
@using (Ajax.BeginForm(options))
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<div class="form-group">
@Html.LabelFor(model => model.Nome, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Nome, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Nome, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Idade, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Idade, new
{
htmlAttributes = new { @class = "form-control" }
})
@Html.ValidationMessageFor(model => model.Idade, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Email, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Email, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Email, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Tel, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
<div class="checkbox">
@Html.EditorFor(model => model.Tel)
@Html.ValidationMessageFor(model => model.Tel, "", new { @class = "text-danger" })
</div>
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.DataNas, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
<div class="checkbox">
@Html.EditorFor(model => model.DataNas)
@Html.ValidationMessageFor(model => model.DataNas, "", new { @class = "text-danger" })
</div>
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.CP, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
<div class="checkbox">
@Html.EditorFor(model => model.CP)
@Html.ValidationMessageFor(model => model.CP, "", new { @class = "text-danger" })
</div>
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Localidade, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
<div class="checkbox">
@Html.EditorFor(model => model.Localidade)
@Html.ValidationMessageFor(model => model.Localidade, "", new { @class = "text-danger" })
</div>
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Mensagem, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
<div class="checkbox">
@Html.EditorFor(model => model.Mensagem)
@Html.ValidationMessageFor(model => model.Mensagem, "", new { @class = "text-danger" })
</div>
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
<label id="labelAjaxStatus" class="alert-warning"></label>
</div>
</div>
</div>
}
<div>
@Html.ActionLink("Ver Lista", "User")
</div>
<script type="text/javascript">
var isError = false;
function OnBeginMethod() {
$("#labelAjaxStatus").text("Carregar ....");
}
function OnFailtureMethod(error) {
$("#labelAjaxStatus").text("Ocorreu um erro." + error.responseText);
isError = true;
}
function OnSuccessMethod(data) {
$("#labelAjaxStatus").text("Dados foram guardados com sucesso!");
$("#Nome").val('');
$("#Idade").val('');
$("#Email").val('');
$("#Tel").val('');
$("#DataNas").val('');
$("#CP").val('');
$("#Localidade").val('');
$("#Mensagem").val('');
}
function OnCompleteMethod(data, status) {
if (!isError) {
$("#labelAjaxStatus").text("Status do processo: " +
status);
}
}
</script>
@Scripts.Render("~/bundles/jqueryval")
포르투갈어는 신경 쓰지 마십시오. 아무도 내가 뭘 잘못하고 있는지 알아?
Contact
사용하려면 컨트롤러 작업에서 다음 코드 스 니펫을 제거해야 합니다.ajax
if (!Request.IsAjaxRequest())
{
Response.StatusCode = (int)System.Net.HttpStatusCode.BadRequest;
return Content("Sorry, this method can't be called only from AJAX.");
}
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다