我想将我的 ViewModel 从 View 传递给控制器,因为我正在使用 Ajax,我的代码如下,我必须显示警报框,并且我收到一个错误为“无效的 JSON 原语:信息”。
控制器:
[HttpPost]
public JsonResult Test(OData.FtpAccount info) {
try {
string FileName = Utils.File.TempName + ".txt";
FtpClient ftp = GetClient(info);
UnicodeEncoding uni = new UnicodeEncoding();
byte[] guid = uni.GetBytes(Utils.File.TempName);
FileName = info.Root + (info.Root.EndsWith("/") ? "" : "/") + FileName;
ftp.Upload(GetTempFile(guid),FileName); //Upload File to Ftp in FtpPath Directory.
string url = info.GetHttpUrl(FileName);
byte[] result = Utils.Web.ReadByte(new System.Uri(url));
ftp.FtpDelete(FileName);
if (uni.GetString(result) == uni.GetString(guid)) {
return Json(new{ success=true});
} else {
return Json(new { warning = true, message = "Warning : Test Upload worked, Test Delete Worked, Http Access of File did not return same content as uploaded." });
}
} catch (System.Exception ex) {
return Json(new { error = true, message = "Ftp Test Failed : " + ex.Message });
}
}
看法:
@model VZDev.ViewModels.FtpAccountViewModel
@{
ViewBag.Title = "Watch";
var val = Json.Encode(Model);
}
<div class="control-group">
<div class="controls">
<button type="button" class="btn" id="test"><i class="icon-test"></i> Test</button>
</div>
</div>
}
<script type="text/javascript">
$(function () {
$("#test").click(function () {
var check=@Html.Raw(val);
$.ajax({
type: 'post',
url: rootURL + 'Ftp/Test',
data: {info:JSON.stringify(check)},
contentType: 'application/json; charset=utf-8',
dataType: "json",
success: function (data) {
alert(data);
}
});
});
});
</script>
模型:
公共部分类 FtpAccount {
[DataMember(Order = 1)]
[ScaffoldColumn(false),DatabaseGenerated(DatabaseGeneratedOption.Identity),Key,UIHint("Id"),Display(Name="Id")]
[Column("ID")]
public long ID{get;set;}
[DataMember(Order = 2)]
[UIHint("Service Provider"),Display(Name="Service Provider"),Required(ErrorMessage="Service Provider is required"),StringLength(100)]
[Column("ServiceProvider")]
public string ServiceProvider{get;set;}
[DataMember(Order = 3)]
[UIHint("Ftp Path"),Display(Name="Ftp Path"),Required(ErrorMessage="Ftp Path is required"),StringLength(500)]
[Column("FtpPath")]
public string FtpPath{get;set;}
}
}
现在在这里我想将我的 ViewModel 从视图传递到控制器。提前致谢!!!