the "create" part is giving me a headache
Controller part:
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create(
[Bind("EnrollmentDate,FirstMidName,LastName")] Student student)
{
try
{
if (ModelState.IsValid)
{
_context.Add(student);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
}
catch (DbUpdateException /* ex */)
{
//Log the error (uncomment ex variable name and write a log.
ModelState.AddModelError("", "Unable to save changes. "
"Try again, and if the problem persists "
"see your system administrator.");
}
return View(student);
}
Create.cshtml
@model ContosoUniversity.Models.Student
@{
ViewData["Title"] = "Create";
}
<h1>CreateView</h1>
<h4>Student</h4>
<hr />
<div >
<div >
<form asp-action="Create">
<div asp-validation-summary="ModelOnly" ></div>
<div >
<label asp-for="LastName" ></label>
<input asp-for="LastName" />
<span asp-validation-for="LastName" ></span>
</div>
<div >
<label asp-for="FirstMidName" ></label>
<input asp-for="FirstMidName" />
<span asp-validation-for="FirstMidName" ></span>
</div>
<div >
<label asp-for="EnrollmentDate" ></label>
<input asp-for="EnrollmentDate" />
<span asp-validation-for="EnrollmentDate" ></span>
</div>
<div >
<input type="submit" value="Create" />
</div>
</form>
</div>
</div>
<div>
<a asp-action="Index">Back to List</a>
</div>
@section Scripts {
@{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}
if i remove "[HttpPost]" my model get's instantly updated and submitted with empty data and returns to index page
the link to actual tutorial:
thanks
CodePudding user response:
since the action has an [ValidateAntiForgeryToken] attribute you should add the same to the view, and replace form tag with an html helper
@using (Html.BeginForm("Create", "Home", FormMethod.Post))
{
@Html.AntiForgeryToken()
<div asp-validation-summary="ModelOnly" ></div>
.... and so on
}
and IMHO don' t use any bind at your post action, it is never a good idea
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create(Student student)
CodePudding user response:
You only need to add method="post"
to <form></form>
.
<form asp-action="Create" method="post">
<div asp-validation-summary="ModelOnly" ></div>
<div >
<label asp-for="LastName" ></label>
<input asp-for="LastName" />
<span asp-validation-for="LastName" ></span>
</div>
<div >
<label asp-for="FirstMidName" ></label>
<input asp-for="FirstMidName" />
<span asp-validation-for="FirstMidName" ></span>
</div>
<div >
<label asp-for="EnrollmentDate" ></label>
<input asp-for="EnrollmentDate" />
<span asp-validation-for="EnrollmentDate" ></span>
</div>
<div >
<input type="submit" value="Create" />
</div>
</form>
So that the form will include a hidden input which name is __RequestVerificationToken
,which contains the value of AntiForgeryToken.When form submit,the token will be passed to Create action.