MVC와 jQuery 모두에 매우 새롭기 때문에이 작업을 수행하는 방법을 잘 모르겠습니다. 나는 ajax 포스트 백과 함께 (다소) 작동하는 모달 대화 양식을 함께 만들었습니다. 이틀 동안 검색했지만 훌륭한 MVC + jQuery 예제를 찾지 못했습니다. 예상대로 데이터가 삽입되며, 제가 사용하기 힘든 UI 일뿐입니다.
Index와 Create의 두 가지 뷰가 있습니다. Index는 Razor로 결과를 반복하는 일반 테이블 내의 모든 레코드를 나열합니다. Create는 모달 대화 상자에로드하는 삽입 양식입니다.
@model IEnumerable<MyProject.Models.StockIndex>
@{
ViewBag.Title = "Admin: Stock Index Home";
Layout = "~/Views/Shared/_LayoutAdmin.cshtml";
}
<h2>View Stock Indices</h2>
<p>
<a href="#" id="createLink">Create New</a>
<div id="createStockIndexForm"></div>
</p>
<table class="table">
<tr>
<th>
@Html.DisplayNameFor(model => model.Name)
</th>
<th>
@Html.DisplayNameFor(model => model.Description)
</th>
<th></th>
</tr>
@foreach (var item in Model)
{
<tr>
<td>
@Html.DisplayFor(modelItem => item.Name)
</td>
<td>
@Html.DisplayFor(modelItem => item.Description)
</td>
<td>
@Html.ActionLink("Edit", "Edit", new { id = item.Id }) |
@Html.ActionLink("Details", "Details", new { id = item.Id }) |
@Html.ActionLink("Delete", "Delete", new { id = item.Id })
</td>
</tr>
}
</table>
@section Scripts {
<script>
$('#createLink').on('click', function () {
$("#createStockIndexForm").dialog({
autoOpen: true,
position: { my: "center", at: "top+350", of: window },
width: 600,
resizable: false,
title: 'Create Stock Index',
modal: true,
open: function () {
$(this).load('@Url.Action("Create", "AdminStockIndex")');
}
});
return false;
});
</script>
}
컨트롤러 작업 :
public ActionResult Create()
{
var model = new StockIndexEditViewModel()
{
StockIndices = GetIndices()
};
return View(model);
}
[HttpPost]
public ActionResult Create(StockIndexEditViewModel model)
{
if (ModelState.IsValid)
{
...
}
return PartialView(model);
}
대화 상자에로드 된 "만들기"양식 (위) :
@model MyProject.Models.StockIndexEditViewModel
@{
ViewBag.Title = "CreatePartial";
Layout = "~/Views/Shared/_LayoutAdmin.cshtml";
}
<h2>CreatePartial</h2>
@using (Html.BeginForm("Create", "AdminStockIndex", FormMethod.Post, new { id = "createForm" }))
{
@Html.AntiForgeryToken()
<div id="result"></div>
<div class="form-horizontal">
<h4>StockIndexEditViewModel</h4>
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<div class="form-group">
@Html.LabelFor(model => model.SelectedParentId, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownListFor(model => model.SelectedParentId, Model.StockIndices, "- Select One -", new { @class = "form-control" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Description, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Description, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Description, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" id="createButton" class="btn btn-default" />
</div>
</div>
</div>
}
@section Scripts {
<script>
$("#createForm").on("submit", function (event) {
event.preventDefault();
$.ajax({
url: this.action,
type: this.method,
async: true,
data: $(this).serialize(),
success: function (data) {
if (data) {
var createForm = $("#createStockIndexForm").dialog();
createForm.dialog("close");
}
else {
$("#result").append("Something went fail.");
}
}
});
});
</script>
}
모달 대화 상자는 닫히지 않고 항상 비어 있습니다. Firebug를 사용하여 Firefox에서 테스트 할 때 가끔이 오류가 표시되지만 매번 발생하지는 않습니다.
InvalidAccessError : 매개 변수 또는 작업이 기본 개체에서 지원되지 않습니다.
검색 할 때 FF가 규칙을 시행하고 다른 브라우저는 그렇지 않을 수있는 CORS 문제라는 것을 알 수 있습니다. 오류가 항상 발생하는 것은 아니며 무작위로 나타나는 것이 답답합니다. Chrome에서 동일하게 작동하지만 JS 콘솔에서 오류가 발생하지 않습니다.
첫째, 이걸 어떻게 풀까요? 둘째, 플러그인없이 ajax를 통해 상위 페이지의 테이블을 새로 고치는 방법이 있습니까?
최신 정보:
Eckert의 도움으로 나는 약간의 진전을 이루었습니다.
저는 MVC Ajax 도우미를 피하고 "순수한"jQuery 접근 방식을 고수하려고합니다. Index의 레코드 목록을 PartialView가 포함 된 div로 대체했습니다.
<div id="stockIndices">
@Html.Partial("_StockIndices", Model)
</div>
jQuery 대화 상자의 닫기 속성을 사용하여 div를 다시로드하여 기본 테이블 새로 고침이 작동합니다.
$('#createLink').on('click', function () {
$("#createStockIndexForm").dialog({
autoOpen: true,
position: { my: "center", at: "top+400", of: window },
width: 600,
resizable: false,
title: 'Create Stock Index',
modal: true,
open: function () {
$(this).load('@Url.Action("Create", "AdminStockIndex")');
},
close: function () {
$("#stockIndices").load('@Url.Action("GetStockIndices", "AdminStockIndex")');
}
});
return false;
});
모달 대화 상자를 수동으로 닫으면 div가 내가 원하는대로 다시로드됩니다. 큰! 이제 양식이 게시 될 때 대화 상자를 닫을 수 있다면 설정됩니다. 작동하지 않습니다.
$("#createStockIndexForm").dialog("close");
Firebug는 오류를보고합니다.
오류 : 초기화 전에 대화 상자에서 메서드를 호출 할 수 없습니다. 'close'메소드를 호출하려고했습니다.
Eckert가 제안한 MVC Ajax 도우미를 사용하는 대신 "순수한"jQuery Ajax 접근 방식을 유지하면서 원하는 모든 것을 얻을 수있는 방법을 찾았습니다. 그러나 그의 제안은 나를 해결책으로 이끌었습니다. 큰 감사를 드린다!
컨트롤러에서 PartialView를 만들었습니다.
public ActionResult GetStockIndices()
{
_service = new StockIndexService();
var data = _service.GetAll();
return PartialView("_StockIndices", data);
}
... 그리고 그 관점 :
@model IEnumerable<MyApp.Models.StockIndex>
<table class="table">
<tr>
<th>
@Html.DisplayNameFor(model => model.Name)
</th>
<th>
@Html.DisplayNameFor(model => model.Description)
</th>
<th></th>
</tr>
@foreach (var item in Model)
{
<tr>
<td>
@Html.DisplayFor(modelItem => item.Name)
</td>
<td>
@Html.DisplayFor(modelItem => item.Description)
</td>
<td>
@Html.ActionLink("Edit", "Edit", new { id = item.Id }) |
@Html.ActionLink("Details", "Details", new { id = item.Id }) |
@Html.ActionLink("Delete", "Delete", new { id = item.Id })
</td>
</tr>
}
</table>
그런 다음 닫을 때 부분보기를로드하도록 모달 대화 상자 스크립트를 변경했습니다. 다음은 후손을위한 전체 인덱스보기입니다.
@model IEnumerable<MyApp.Models.StockIndex>
@{
ViewBag.Title = "Admin: Stock Index Home";
Layout = "~/Views/Shared/_LayoutAdmin.cshtml";
}
<h2>View Stock Indices</h2>
<p>
<a href="#" id="createLink">Create New</a>
<div id="createStockIndexForm"></div>
</p>
<div id="stockIndices">
@Html.Partial("_StockIndices", Model)
</div>
@section Scripts {
<script>
var _dialog;
$('#createLink').on('click', function () {
_dialog = $("#createStockIndexForm").dialog({
autoOpen: true,
position: { my: "center", at: "top+400", of: window },
width: 600,
resizable: false,
title: 'Create Stock Index',
modal: true,
open: function () {
$(this).load('@Url.Action("Create", "AdminStockIndex")');
},
close: function () {
$("#stockIndices").load('@Url.Action("GetStockIndices", "AdminStockIndex")');
}
});
return false;
});
</script>
}
전역 "_dialog"변수를 확인하십시오. 이렇게하면 Create 양식에서 대화 상자에 액세스 할 수 있으므로 닫을 수 있습니다.
<script>
$("#createForm").on("submit", function (event) {
event.preventDefault();
$.ajax({
url: this.action,
type: this.method,
async: true,
data: $(this).serialize(),
success: function (data) {
if (data) {
if (_dialog) {
_dialog.dialog("close");
}
}
else {
$("#result").append("Error! Record could not be added.");
}
},
error: function (error) {
console.error(error);
}
});
});
</script>
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다