问题描述
我想一个模型传递给我的控制器与Ajax调用。
我已经看了由Laviak在以下问题提供了答案,但没有能够得到它的工作。
我收到的Ajax调用运行时的模型变量未定义的错误。我已经证实,辅助类被调用,并返回一个字符串。是不是因为AJAX调用是一个.js文件里面呢?为什么不确定?
我的code:
的Site.Master:
<脚本类型=测试/ JavaScript的>
VAR模型='<%= Model.ToJson()%GT;';
< / SCRIPT>
帮助器类:
公共静态字符串的toJSON(这个obj对象)
{
弦模型=新的JavaScriptSerializer()序列化(OBJ)。
回归模型;
}
的Javascript文件,
VAR GstTotal = $阿贾克斯(
{
输入:POST,
异步:假的,
网址:BASE_APP_URL +'WashTicket / GetTaxTotal',
传统:真正的,//则需要此设置将数组传递给控制器
//数据:MODEL
数据:{
AMODEL:MODEL
}
})responseText的;
操作方法:
公共字符串GetTaxTotal(字符串AMODEL)
{ 返回;
}
请确保所包含AJAX调用JavaScript文件定义了剧本后纳入模型
在你的主文件变量:
<脚本类型=测试/ JavaScript的>
VAR模型='<%= Model.ToJson()%GT;';
< / SCRIPT>
<脚本类型=文/ JavaScript的SRC =<%= Url.Content(〜/脚本/ myscript.js)%>>< / SCRIPT>
此外,我会建议你服用一看下面这说明了如何使用JSON AJAX请求到控制器通过复杂的对象图文章。
I'm trying to pass a model to my controller with an ajax call.
I've looked at the answer provided by Laviak in the following question but was not able to get it to work.
I'm getting an undefined error with the MODEL variable when the ajax call runs. I've confirmed that the helper class is being called and is returning a string. Is it because the AJAX call is inside a .js file? Why is it undefined?
My Code:
Site.Master:
<script type="test/javascript">
var MODEL = '<%= Model.ToJson() %>';
</script>
Helper Class:
public static string ToJson(this Object obj)
{
string model = new JavaScriptSerializer().Serialize(obj);
return model;
}
Javascript file:
var GstTotal = $.ajax(
{
type: 'POST',
async: false,
url: BASE_APP_URL + 'WashTicket/GetTaxTotal',
traditional: true, //This setting is required to pass arrays to the Controller
// data: MODEL
data: {
aModel: MODEL
}
}).responseText;
Action method:
public string GetTaxTotal(string aModel)
{
return "";
}
Make sure that the javascript file that is containing the AJAX call is included after the script that defines the MODEL
variable in your master file:
<script type="test/javascript">
var MODEL = '<%= Model.ToJson() %>';
</script>
<script type="text/javascript" src="<%= Url.Content("~/scripts/myscript.js") %>"></script>
Also I would recommend you taking a look at the following article which illustrates how to pass complex object graphs using JSON AJAX request to a controller.
这篇关于ASP.NET MVC传递模型AJAX到控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!