반응형
Asp에서 AJAX를 사용하여 양식을 제출합니다.넷 mvc 4
저는 asp.net 을 배우려고 노력하고 있으며 지금까지 다른 페이지 내용을 새로 고치지 않고 로드할 수 있습니다.Ajax.Actionlink그리고.AjaxOptions()하지만 양식을 제출할 때 아약스를 사용하는 방법을 알 수 없습니다.저는 많은 검색을 했지만 적절한 해결책을 찾을 수 없었습니다.여기 내 암호야
컨트롤러 페이지
namespace CrudMvc.Controllers
{
public class HomeController : Controller
{
sampleDBEntities db = new sampleDBEntities();
//
// GET: /Home/
public ActionResult Index()
{
return View(db.myTables.ToList());
}
public PartialViewResult Details(int id = 0)
{
myTable Table = db.myTables.Find(id);
return PartialView(Table);
}
[HttpGet]
public PartialViewResult Create()
{
return PartialView();
}
[HttpPost]
public ActionResult Create(myTable table)
{
if (ModelState.IsValid)
{
db.myTables.Add(table);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(table);
}
protected override void Dispose(bool disposing)
{
db.Dispose();
base.Dispose(disposing);
}
}
}
Index페이지 보기
@model IEnumerable<CrudMvc.Models.myTable>
@{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<script src="~/Scripts/jquery-1.7.1.min.js"></script>
<script src="~/Scripts/jquery.unobtrusive-ajax.min.js"></script>
<h2>Index</h2>
<p>
@Ajax.ActionLink("Add New", "Create", new AjaxOptions()
{
HttpMethod = "GET",
UpdateTargetId = "info",
InsertionMode = InsertionMode.Replace
})
</p>
<div id="main">
<table>
<tr>
<th>
@Html.DisplayNameFor(model => model.name)
</th>
<th>Action</th>
</tr>
@foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.name)
</td>
<td>
@Ajax.ActionLink("Details", "Details", new{ id=item.id}, new AjaxOptions()
{
HttpMethod = "GET",
UpdateTargetId = "info",
InsertionMode = InsertionMode.Replace
})
</td>
</tr>
}
</table>
</div>
<div id="info"></div>
Create페이지 보기
@model CrudMvc.Models.myTable
@{
ViewBag.Title = "Create";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Create</h2>
@using (Html.BeginForm()) {
@Html.ValidationSummary(true)
<fieldset>
<legend>myTable</legend>
<div class="editor-label">
@Html.LabelFor(model => model.id)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.id)
@Html.ValidationMessageFor(model => model.id)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.name)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.name)
@Html.ValidationMessageFor(model => model.name)
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
<script>
var form = $('#main');
$.ajax({
cache: false,
async: true,
type: "POST",
url: form.attr('action'),
data: form.serialize(),
success: function (data) {
alert(data);
}
});
</script>
<div>
@Html.ActionLink("Back to List", "Index")
</div>
@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
}
여기 완전한 예가 있습니다.
간단한 모델을 만들어 보겠습니다.
public class Details
{
public string Name { get; set; }
public string Email { get; set; }
}
이제 다음을 사용하여 GET 및 POST 요청을 수행할 몇 가지 작업을 생성합니다.AJAX BEGINFORM-
static List<Details> details = new List<Details>();
public ActionResult GetMe()
{
return View();
}
public ActionResult SaveData(Details d)
{
details.Add(d);
return Json(details.Count, JsonRequestBehavior.AllowGet);
}
그런 다음 Ajax를 호스팅할 간단한 보기를 생성합니다.시작 양식() -
@model RamiSamples.Controllers.Details
@{
ViewBag.Title = "Ajax";
}
<h2>Ajax</h2>
<script src="~/Scripts/jquery-1.8.2.min.js"></script>
<script src="~/Scripts/jquery.unobtrusive-ajax.min.js"></script>
@using (Ajax.BeginForm("SaveData", new AjaxOptions()
{
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "dane"
}))
{
@Html.AntiForgeryToken()
@Html.ValidationSummary(true)
<fieldset>
<legend>Details</legend>
<div class="editor-label">
@Html.LabelFor(model => model.Name)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Name)
@Html.ValidationMessageFor(model => model.Name)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.Email)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Email)
@Html.ValidationMessageFor(model => model.Email)
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
<div id="dane">
Number of Details :
</div>
이제 페이지가 렌더링되면 -

이제 데이터를 입력하고 생성 버튼을 클릭하면 -

그러면 아래와 같이 페이지가 자동으로 추가 개수로 업데이트됩니다.

언급URL : https://stackoverflow.com/questions/26191774/submit-form-using-ajax-in-asp-net-mvc-4
반응형
'codememo' 카테고리의 다른 글
| 저장 프로시저와 보기의 차이점은 무엇입니까? (0) | 2023.07.27 |
|---|---|
| Javascript를 사용하여 비활성화된 특성을 입력 요소에 추가합니다. (0) | 2023.07.27 |
| 예외영구 저장소에서 세션 로드 (0) | 2023.07.27 |
| 오라클: 블롭이 있는 테이블을 다시 가져올 수 있는 .sql 파일로 내보냅니다. (0) | 2023.07.27 |
| 제너레이터 이해는 정확히 어떻게 작동합니까? (0) | 2023.07.27 |