MVC下讀取XML生成動態表單的例子
我們來看下面的例子:
接著上次的MVCMembership來講
我們首先添加一個目錄XML。然后添加View:
1.checkXml.aspx 用來檢查我們輸入的XML格式(利用XSD檢查)
2.New.aspx 用來新增XML表單的
3.Show.aspx 用來顯示XML表單的
4.ShowResult.aspx 用來顯示XML表單提交的結果的
一、數據庫結構
要用到動態的表單,這里我們利用Sqlserver2005的XML類型來保存,建表的SQL如下:
use Test
/*==============================================================*/
/* DBMS name: Microsoft SQL Server 2005 */
/* Created on: 2009/5/8 7:56:50 */
/*==============================================================*/
if exists (select 1
from sysindexes
where id = object_id('XMLFORM')
and name = 'IDX_XML'
and indid > 0
and indid < 255)
drop index XMLFORM.IDX_XML
go
if exists (select 1
from sysindexes
where id = object_id('XMLFORM')
and name = 'IDX_ID'
and indid > 0
and indid < 255)
drop index XMLFORM.IDX_ID
go
if exists (select 1
from sysobjects
where id = object_id('XMLFORM')
and type = 'U')
drop table XMLFORM
go
/*==============================================================*/
/* Table: XMLFORM */
/*==============================================================*/
create table XMLFORM (
ID int identity,
FORMXML xml not null,
constraint PK_XMLFORM primary key (ID)
)
go
declare @CurrentUser sysname
select @CurrentUser = user_name()
execute sp_addextendedproperty 'MS_Description',
'XMLFORM',
'user', @CurrentUser, 'table', 'XMLFORM'
go
/*==============================================================*/
/* Index: IDX_ID */
/*==============================================================*/
create unique index IDX_ID on XMLFORM (
ID ASC
)
go
/*==============================================================*/
/* Index: IDX_XML */
/*==============================================================*/
create PRIMARY XML INDEX IDX_XML on XMLFORM (
FORMXML
)
go
好了我們建了一個名為XMLForm的表,其中ID自增,FORMXML為我們需要的XML表單的內容
二、編寫XML的Controller
XMLController.cs
主要的action
1.New
498)this.style.width=498;" height=148>
498)this.style.width=498;" height=127>
498)this.style.width=498;" height=127> 498)this.style.width=498;" height=127>
[AcceptVerbs(HttpVerbs.Post), ValidateInput(false)]
public ActionResult New(string xmlContent)
{
System.Threading.Thread.Sleep(2000); //模擬提交等待
xmlContent = Server.UrlDecode(xmlContent);
if (!string.IsNullOrEmpty(xmlContent))
{
//if (!CheckXML(xmlContent, out strError)) //服務器端檢測,如果用了ajax檢測,就沒必要了
//{
// ModelState.AddModelError("_FORM",strError);
// return View();
//}
XMLFormDataContext db = new XMLFormDataContext();
TransactionOptions opt = new TransactionOptions();
ViewData["xmlContent"] = xmlContent;
opt.IsolationLevel = IsolationLevel.Serializable;
using (TransactionScope tran = new TransactionScope(TransactionScopeOption.RequiresNew, opt))
{
XMLFORM f = new XMLFORM();
try
{
f.FORMXML = XElement.Parse(xmlContent);
db.XMLFORMs.InsertOnSubmit(f);
db.SubmitChanges();
var id = db.XMLFORMs.Max(p => p.ID);
ViewData["result"] = "success";
ViewData["id"] = (int)id;
tran.Complete();
return View();
}
catch
{
ViewData["result"] = "failure";
ModelState.AddModelError("_FORM", "envalid xml format");
return View();
}
}
}
else
return View();
}XML:
注意:我們使用了事務,所以不要忘了***要提交。我就是忘了,找了3天錯誤 2.Show
[AcceptVerbs(HttpVerbs.Get)]
public ActionResult Show(int? ID)
{
int nId = 0;
XElement doc = null;
if (int.TryParse(Request["id"], out nId))
{
try
{
XMLFormDataContext db = new XMLFormDataContext();
var q = from f in db.XMLFORMs
where f.ID == nId
select f.FORMXML
;
if (q.Count() > 0)
{
foreach (var qq in q)
{
doc = qq;
}
ViewData["xml"] = doc;
}
else
{
ModelState.AddModelError("_FORM", "Not Exists");
}
ViewData["id"] = nId;
}
catch (Exception e)
{
ModelState.AddModelError("_FORM", e.Message);
}
}
else
{
ModelState.AddModelError("_FORM", "Miss ID");
}
return View();
}
注意這里Show.asp的寫法.不能用< input .../ >直接輸出控件字符串,而要
Response.Write(Html.TextBox(i.Attribute("Name").Value, "", new { @class = "InputNormal" }));否則提交后得不到form的值代碼如下:
<%using (Html.BeginForm())
{ %>
<%=Html.ValidationSummary()%>
Show XML Form
<%} %>
XML內容的檢測
我們可以利用XSD來檢查。
代碼如下
#region 檢查xml
[AcceptVerbs(HttpVerbs.Post), ValidateInput(false)]
public ActionResult checkXML(string xmlContent)
{
string strOut = string.Empty;
int nResult = (CheckXML(xmlContent, out strOut) == true) ? 1 : 0;
DictionarydicResult = new Dictionary ();
dicResult.Add("State", nResult.ToString());
dicResult.Add("Message", strOut);
return Json(dicResult);
}
private bool CheckXML(string xmlContent)
{
bool bResult = true;
if (!string.IsNullOrEmpty(xmlContent))
{
//利用XmlSchemaSet(XSD)檢查XML
XmlSchemaSet validator = new XmlSchemaSet();
validator.Add("", XmlReader.Create(Server.MapPath(Url.Content("~/Models/xmlTest.xsd")))); //Url.Content必須,否則找不到文件
XDocument doc = null;
try
{
doc = XDocument.Parse(xmlContent);
doc.Validate(validator, (sender, e) =>
{
bResult = false;
});
}
catch
{
bResult = false;
}
}
else
bResult = false;
return bResult;
}
private bool CheckXML(string xmlContent, out string outString)
{
bool bResult = true;
string strError = string.Empty;
if (!string.IsNullOrEmpty(xmlContent))
{
//利用XmlSchemaSet(XSD)檢查XML
XmlSchemaSet validator = new XmlSchemaSet();
validator.Add("", XmlReader.Create(Server.MapPath(Url.Content("~/Models/xmlTest.xsd")))); //Url.Content必須,否則找不到文件
XDocument doc = null;
try
{
doc = XDocument.Parse(xmlContent);
doc.Validate(validator, (sender, e) =>
{
strError = e.Message;
bResult = false;
});
}
catch (XmlException e)
{
strError = e.Message;
bResult = false;
}
}
else
bResult = false;
if (!bResult)
outString = strError;
else
outString = "OK";
return bResult;
}
#endregion
這里我們返回json數據,來ajax檢查
$(document).ready(function() {
$("form").submit(function() {
if (jQuery.formValidator.pageIsValid())
$.blockUI({ message: 'Please Wait...
' });
});
if ($("#xmlContent").val() != "")
$("#xmlContent").val(decodeURI($("#xmlContent").val()));
$.formValidator.initConfig();
$("#xmlContent").formValidator({ onshow: "please input xml", onfocus: "xml required", oncorrect: "OK" })
.inputValidator({ min: 1, empty: { leftempty: true, rightempty: true }, onerror: "xml required" })
.ajaxValidator({
type: "post",
url: "checkXML",
datatype: "json",
success: function(responseData) {
if (responseData.State == "1") {
return true;
}
else {
return false;
}
},
buttons: $("#submit"),
error: function() { alert("server busy,try later..."); },
onerror: "XML Format error or same content",
onwait: "XML checking,please wait..."
});
});
function CheckForm() {
result = jQuery.formValidator.pageIsValid();
if (result) {
$("#xmlContent").val(encodeURI($("#xmlContent").val()));
}
return result;
}
注意我們利用了encodeURI,decodeURI進行編碼,來避免A potentially dangerous Request.QueryString value was detected from the client問題
3.***編寫ShowResult
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult ShowResult()
{
StringBuilder sbResult = new StringBuilder();
foreach(string key in Request.Form.Keys)
{
sbResult.AppendLine(string.Format("{0}={1}", key, Request.Form[key]));
}
return Json(sbResult.ToString());
}
很簡單的直接輸出form的內容,你也可以進行你自己的處理,用ajax來避免再次刷新***結果
498)this.style.width=498;" height=127> 498)this.style.width=498;" height=127>
【編輯推薦】