Reputation: 517
I used to develop some applications in C#/Winforms and now I'm trying to learn web development with MVC.
It's a lot of new concepts (JS,Ajax,ASP.net, etc...), so please be tolerent...
I have read a lot and began to work and try, but there is a point that I still don't understand.
For exemple, I want to insert datas in a database via a Form, just insert, nothing else.
The method to insert is in the controller.
The evident method is to use Html helper @Html.BeginForm
. At this step I'm not able to do that without reloading the whole page.
Due to the fact that I didn't find any clear answer, could you please help me.
1-Is it possible with @Html.BeginForm
to do nothing after posting form in order to insert in database (maybe with a specific return type of the action in the controller) or Ajax.BeginForm
is the unique solution ?
2-Same to update a part of a page, is ajax the unique solution ?
Many thanks.
Upvotes: 0
Views: 4269
Reputation:
You can load partial views into a view using Razor or ajax. I use this technique when the same part of the page can have different views - for example, like a tabbed control
You make up a URL in the usual style for MVC. In this example I assume that a HTTP GET on some existing data is performed. For your CREATE GET option, just the controller and action are sufficient. Note that the HTML returned from the action replaces the contents of a DIV elsewhere on the page
var targetUrl = "/MyController/MyAction/" + id + "?extraParameter=" + 123;
//-----------------------------------------
// get content from URL using Ajax
//-----------------------------------------
$.ajax({
url: targetUrl,
type: "get",
success: function (result) {
$("#divPageContent").html(result);
}
});
You can load your CREATE view from the controller as shown above. You'll need a SAVE button in there, when clicked, calls Ajax to POST your values back to the server.
You should use a FORM in your view with an AntiForgeryToken and use an Ajax POST. I don't recommend using a HTTP GET to add or change data.
There are plenty of resources out there to show you how to do that.
Assuming your CREATE process works, you can return any view you like to show the results, back into the same DIV that was used for the creation.
Many developers use this technique, even to the point of single-page websites where all content is dynamically loaded.
For my sites I find most processes work fine without resorting to Ajax. Modern browsers handle content change and flicker quite well. I resort to Ajax for partial views in more complex pages. If you are going the Ajax route, consider a busy indicator - this pops up an icon of your choice when Ajax is working so that your users know the page is doing some work.
$(function () {
$(document).ajaxStart(function () {
$(".processSpinner").show();
});
$(document).ajaxStop(function () {
$(".processSpinner").hide();
});
$(document).ajaxError(function () {
$(".processSpinner").hide();
});
$(".processSpinner").hide();
});
include antiforgerytoken in ajax post ASP.NET MVC
Upvotes: 1
Reputation: 332
I have create one form in asp.net core with post data using ajax It's working Create Partial View
@model Department
<h2>Create</h2>
<script src="~/lib/jquery/dist/jquery.js"></script>
<script src="~/lib/jquery-validation/dist/jquery.validate.js"></script>
<script src="~/lib/jquery-validation-unobtrusive/jquery.validate.unobtrusive.js"></script>
<div class="form-horizontal">
<form asp-action="Create" role="form" asp-controller="Department" asp-antiforgery="true"
data-ajax-success="Bindgrid"
data-ajax="true"
data-ajax-method="POST">
<div class="form-group">
<label class="control-label" asp-for="DepartmentName"></label>
<input class="form-control" type="text" asp-for="DepartmentName" />
<span asp-validation-for="DepartmentName" class="text-danger"></span>
</div>
<input class="btn btn-primary" type="submit" value="Save" />
</form>
</div>
Controller logic
[ValidateAntiForgeryToken()]
[HttpPost]
public JsonResult Create(Department department)
{
if (ModelState.IsValid)
{
Context.Department.Add(department);
Context.SaveChanges();
}
return Json(department);
}
Upvotes: 0
Reputation:
There are a lot of concepts to get your head around. Lets start with two basic choices. Update date using a simple post back or JavaScript and Ajax?
OK, lets go for the first one, a simple create process.
You will need the database table to update. You can create an Entity Framework model from the database. Your application will interact with this up update the table. This is the "M" or model in MVC. You'll also need to create a controller (the "C" in MVC) and a view (the "V" in MVC).
The controller will often contain two methods to perform the work. When a user navigates to the web page, they GET the initial data. All this does is return the view with a null model, so any edit controls are in their default state - e.g. empty text box
[HttpGet]
public ActionResult Create()
{
return View();
}
When the view is saved by the user, another method (with the same name) is called. Note that this is the POST method, so all of the data in the FORM is packaged up into the ModelState. MVC will bind your model for you into the parameters of the method - you can even say which ones to include. The version here uses Async.
The FORM in your view should have an anti-forgery token too, which is the first (hidden) field returned and used by the MVC system - you don't usually see it.
Assuming the data is valid, it is saved to the database (I usually have an underlying business model to do the work to keep the controller clean). If the model is not valid (e.g. missing field), the existing model is passed back to the view for the user to have another go, along with any error messages. Have a look at Data-Annotations to see how to define the valid value ranges.
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Create([Bind(Include = "YourName")] MyData model)
{
if (ModelState.IsValid)
{
await _bs.MyData_UpdateAsync(model);
return RedirectToAction("Index");
}
// return with any errors
return View(model);
}
Finally, you'll need a view from which HTML is dynamically generated and passed to the client browser
@model MyApp.Models.MyData
@{
ViewBag.Title = "Create Something";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<div class="container w-50">
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<div class="form-group">
@Html.LabelFor(model => model.YourName, htmlAttributes: new { @class = "control-label" })
@Html.EditorFor(model => model.YourName, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.YourName, "", new { @class = "text-danger" })
</div>
<div class="d-flex">
<div class="ml-auto">
<input type="submit" value="Create" class="btn btn-primary btn-sm btn-default" />
</div>
</div>
</div>
}
</div>
Upvotes: 0