[英]Using Unobtrusive JQuery validation in MVC3 without Ajax.BeginForm?
[英]MVC3 using Ajax.BeginForm not sending ViewModel to controller
我不太了解如何使用Ajax.BeginForm以及與控制器的交互。 這是我的情況。 我有一個帶有項目列表的頁面。 當我單擊項目旁邊的“編輯”時,將打開一個jquery對話框,其中包含包含要編輯字段的強類型部分視圖。 單擊更新時,如果視圖模型有效,我想保存所做的更改,或者在必要時顯示錯誤。 我的問題是單擊更新時。 我無法將序列化數據作為視圖模型發送到控制器。
編輯:好的,我發現了1個問題。 我的表單標簽格式不正確,因此表單字段不在表單范圍內。 現在我對表格的序列化有問題。 我收到此消息:無效的JSON原語:section_id。
這是我的序列化字符串:
section_id = 74&section_name_en = The + CF + Mission&section_name_fr = La + mission + des + FC&norm_tab_name_en = Introduction&norm_tab_name_fr = Introduction&section_tab_id = 2&active = true&active = false&display_order =%&text_%3%C&3 %2Fdiv%3E%0D%0A%0D%0A%3Cdiv%3E%3Cstrong%3EThe + mission + of + the + thecanadadian + Force + is%to%3A%3C%2Fstrong%3E%3C%2Fdiv%3E%0D %0A%0D%0A%3Cul + style%3D%22list-style %% 3A + disc%22%3E%0D%0A%09%3Cli%3Eprotect + Canada%2C%3C%2Fli%3E%0D%0A %09%3Cli%3Edefend + North + America + in + co + operation + with + the + US%2C + and%3C%2Fli%3E%0D%0A%09%3Cli%3Econtributed + to + international + peace + and +安全性。%3C%2Fli%3E%0D%0A%3C%2Ful%3E%0D%0A%0D%0A%3Cdiv%3E%3Cbr +%2F%3E%0D%0AOn + any + given + day%2C +大約+ 8%2C000 +加拿大+部隊+成員+-+一名+三分之一+我們的+可部署的+部隊+-++正在為%2C +從事+或+從+一個+海外+任務+的准備。 + At + home%2C + Canadian + Force + can + bring + the + best + available + military + resources + from + acr oss + Canada + to + bear + on + a +危機+或+威脅%2C +在任何地方發生%2C +全國范圍內。%3Cbr +%2F%3E%0D%0A%3Cbr +%2F%3E%0D %0A + Canadian + Force + now + has + an +敏捷%2C +高度准備就緒+特殊+運營+ Force +有能力+有能力+跨越+頻譜+沖突+在家中+國外%3B + it +由+ joint + Task + Force + 2 +(JTF-2)%2C + the + Special + Operations + Aviation + Squadron%2C + the + Joint + Nuclear%2C + Biological + and +化學+國防+公司%2C +和+加拿大+特殊+行動+軍團。%3C%2Fdiv%3E%0D%0A&content_text_fr =%3Cdiv%3E%26nbsp%3B%3C%2Fdiv%3E%0D%0A %0D%0A%3Cdiv%3E%3Cstrong%3ELa +任務+ des + Force + canadiennes + est + de%3C%2Fstrong%3E%3C%2Fdiv%3E%0D%0A%0D%0A%3Cul%3E%0D %0A%09%3Cli%3Eprot%26eacute%3Bger + le + Canada%2C%3C%2Fli%3E%0D%0A%09%3Cli%3Ed%26eacute%3Bfendre + l%26%2339%3BAm%26eacute%3Brique + du + Nord + en +合作+ avec + les +%26Eacute%3Btats-Unis + et%3C%2Fli%3E%0D%0A%09%3Cli%3Ede + favoriser + la + paix + et + la + s%26eacute %3Bcurit%26eacute%3B + dans + le + monde。%3C%2Fli%3E%0D%0A%3C%2Ful%3E%0D%0A%0D%0A%3Cdiv%3E%3Cbr + %2F%3E%0D%0AChaque + jour%2C + environ + 8 + 000 + militaires + des + Forces + canadiennes +(FC)%2C + soit +%26agrave%3B + peu + pr%26egrave%3Bs + le + tiers + de + nos + forces + d%26eacute%3Bployables%2C + se + pr%26eacute%3Bparent +%26agrave%3B + une + mission +%26agrave%3B + 1%26%2339%3B%26eacute%3Btranger%2C + y + Participent + sur + place + ou + en + reviennent。+ Au + pays%2C + les + Force + canadiennes + peuvent + mettre +%26agrave%3B + profit + les + meilleures + resources + militaires + de + partout + au + Canada %2C + en + cas + de + crise + ou + de +威脅%2C + n%26%2339%3Bimporte + o%26ugrave%3B + sur + l%26%2339%3Bensemble + du + territoire。%3Cbr +% 2F%3E%0D%0A%3Cbr +%2F%3E%0D%0ALes + Force + canadiennes + se + sont + dot%26eacute%3Bes + d%26%2339%3Bune + capaccit%26eacute%3B + d%26% 2339%3Bop%26eacute%3Brations + sp%26eacute%3Bciales +%26eacute%3Blargie + et + am%26eacute%3Blior%26eacute%3Be + capables + d%26%2339%3Bintervenir + rapantment + et + pouvant + mener + des + op%26eacute%3Brations + sur + tout + 1%26%2339%3B%26eacute%3Bventail + des + conflits%2C + au + Canada + comme +%26agrave%3B + 1%26%2339%3B%26eacute%3Btranger +% 3B + ces + forces + compren nent + la + Deuxi%26egrave%3Bme + Force + op%26eacute%3Brationnelle + interarm%26eacute%3Bes +(FOI-2)%2C + 1%26%2339%3BEscadron + d%26%2339%3Bop%26eacute%3Brations + sp%26eacute%3Bciales +(航空)%2C + la + Compagnie + interarm%26eacute%3Bes + de + d%26eacute%3Bfense + nucl%26eacute%3Baire%2C + biologique + et + chimique + et + le + R% 26eacute%3Bgiment + d%26%2339%3Bop%26eacute%3Brations + sp%26eacute%3Bciales + du + Canada。%3C%2Fdiv%3E%0D%0A
這是我的模型定義:
public class SectionContent
{
private int _section_tab_id;
private int _section_id;
private string _section_name_en;
private string _section_name_fr;
private string _tab_title_en;
private string _tab_title_fr;
private int _display_order;
private string _norm_tab_name_en;
private string _norm_tab_name_fr;
private string _banner;
private bool _active;
private int _content_id;
private string _content_text_en;
private string _content_text_fr;
[snip]
}
這是我的PartialView:
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<ForcesCMS.Models.SectionContent>" %>
<%=Html.ValidationSummary(MyLabels.labels.please_correct_markedfields, new { @class = "validation" })%>
<fieldset>
<legend><%=Model.tab_title_en%></legend>
<input type="hidden" id="section_id" name="section_id" value="<%= Model.section_id%>" />
<input type="hidden" id="section_name_en" name="section_name_en" value="<%= Model.section_name_en%>" />
<input type="hidden" id="section_name_fr" name="section_name_fr" value="<%= Model.section_name_fr%>" />
<input type="hidden" id="norm_tab_name_en" name="norm_tab_name_en" value="<%= Model.norm_tab_name_en%>" />
<input type="hidden" id="norm_tab_name_fr" name="norm_tab_name_fr" value="<%= Model.norm_tab_name_fr%>" />
<input type="hidden" id="content_id" name="content_id" value="<%= Model.content_id%>" />
<div class="formrowFull">
<div class="formcol">
<label for="section_tab_id" class="inline"><%=MyLabels.labels.id%></label>
<%= Html.TextBoxFor(model => model.section_tab_id, new { @class = "smallBoxReadonly" })%>
</div>
<div class="formcol">
<label for="active" class="inline"><%=MyLabels.labels.active%></label>
<%=Html.CheckBoxFor(model => model.active)%>
</div>
</div>
<div class="formrowFull">
<div class="formcol">
<label for="display_order" class="inline mandatory"><%=MyLabels.labels.display_order%></label>
<%= Html.TextBoxFor(model => model.display_order, new { @class = "smallBox" })%>
<%= Html.ValidationMessageFor(model => model.display_order)%>
</div>
<div class="formcol">
<label for="banner" class="inline"><%=MyLabels.labels.banner%></label>
<%= Html.TextBoxFor(model => model.banner, new { @class = "largeBox" })%>
</div>
</div>
<div class="formrowFull">
<div class="formcol">
<label for="tab_title_en" class="mandatory"><%=MyLabels.labels.title_en%></label>
<%= Html.TextBoxFor(model => model.tab_title_en, new { @class = "largeBox" })%>
<%= Html.ValidationMessageFor(model => model.tab_title_en)%>
</div>
<div class="formcol">
<label for="tab_title_fr" class="mandatory"><%=MyLabels.labels.title_fr%></label>
<%= Html.TextBoxFor(model => model.tab_title_fr, new { @class = "largeBox" })%>
<%= Html.ValidationMessageFor(model => model.tab_title_fr)%>
</div>
</div>
<div class="formrowFull">
<div class="formcol">
<input type="hidden" name="content_id" id="content_id" value="<%=Model.content_id %>" />
<%= Html.LabelFor(model => model.content_text_en)%>
<%= Html.TextAreaFor(model => model.content_text_en, new { @class = "ckeditor_tpl" })%>
<%= Html.ValidationMessageFor(model => model.content_text_en)%>
</div>
<div class="formcol">
<%= Html.LabelFor(model => model.content_text_fr)%>
<%= Html.TextAreaFor(model => model.content_text_fr, new { @class = "ckeditor_tpl" })%>
<%= Html.ValidationMessageFor(model => model.content_text_fr)%>
</div>
</div>
</fieldset><%}%>
接下來,我將發布我的Controller和腳本,這些都是令我困惑的部分。
控制器:
[HttpGet]
// Called when click on Edit link - data displayed in modal dialog
public PartialViewResult AddEditRecord(int id)
{
ViewData["IsUpdate"] = true;
SectionContent sc = ContentHandler.GetTabContent(id);
return PartialView("ContentForm", sc);
}
[HttpPost]
[ValidateInput(false)]
// Called when clicking on Update in modal
public PartialViewResult AddEditRecord(SectionContent sc, string cmd)
{
// Never valid because model (sc) is always null
if (ModelState.IsValid)
{
try
{
//update
int result = ContentHandler.UpdateSectionContent(sc);
return PartialView("ContentForm");
}
catch { }
}
if (Request.IsAjaxRequest())
{
return PartialView("ContentForm", sc);
}
else
{
return PartialView("ContentForm");
}
}
腳本:
$.ajaxSetup({ cache: false });
function DoAjaxUpdate() {
$.ajax({
url: $("#frmEdit").attr("action"),
type: 'POST',
dataType: "json",
contentType: 'application/json',
data: $("#frmEdit").serialize(),
success: function (result) {
$('#dialog-edit').html(result);
}
});
}
$(".editDialog").live("click", function (e) {
var url = $(this).attr('href');
$("#dialog-edit").dialog({
title: 'Edit Tab and Content',
autoOpen: false,
resizable: false,
height: 800,
width: 600,
show: { effect: 'drop', direction: "up" },
modal: true,
draggable: true,
open: function (event, ui) {
$(this).load(url);
},
close: function (event, ui) {
$(this).dialog('close');
},
buttons: {
"Update": function () {
DoAjaxUpdate();
},
"Cancel": function () {
$(this).dialog('close');
}
}
});
$("#dialog-edit").dialog('open');
return false;
});
如何正確序列化表單,以便控制器將其識別為有效的ViewModel。 然后,一旦解決,我應該在Controller動作中做什么? JsonResult? 返回PartialView? 動作結果?
我一直在大量的SO帖子和其他網站上進行搜索,最近幾天我嘗試了很多事情,但是沒有運氣。 任何幫助表示贊賞。 謝謝 !
在使用form標記糾正錯誤之后,我終於找到了正確的jquery代碼來序列化我的表單並將其作為viewmodel發送到控制器。
這是更正的腳本:
function DoAjaxUpdate() {
$.ajax({
url: $("#frmEdit").attr("action"),
type: "POST",
data: $('#frmEdit :input').serialize(),
success: function (result) {
$('#dialog-edit').html(result);
}
});
}
$(".editDialog").live("click", function (e) {
var url = $(this).attr('href');
$("#dialog-edit").dialog({
title: 'Edit Tab and Content',
autoOpen: false,
resizable: false,
height: 800,
width: 600,
show: { effect: 'drop', direction: "up" },
modal: true,
draggable: true,
open: function (event, ui) {
$(this).load(url);
},
close: function (event, ui) {
$(this).dialog('close');
},
buttons: {
"Update": function () {
DoAjaxUpdate();
},
"Cancel": function () {
$(this).dialog('close');
}
}
});
$("#dialog-edit").dialog('open');
return false;
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.