【发布时间】:2013-02-04 18:43:11
【问题描述】:
我正在尝试使用 Ajax.BeginForm 功能。
表单已正确发布,但我需要从控制器操作中检索 json 格式的数据,并使用操作结果消息刷新 div。
我在 Stackoverflow 中找到了一些建议,但没有一个有用。
这是找到的建议:
var data = content.get_response().get_object();
But it didn't work for me。而且我相信今天已弃用,仅适用于 MVC 2 及更低版本。 我当前的 MVC 版本是 3。
这是一段代码:
<script type="text/javascript">
function fnCompleted(data){
if(data.Success)
$("#somediv").html(data.StatusMessage).addClass("success");
else
$("#somediv").html(data.StatusMessage).addClass("error");
}
</script>
@{
var ajaxOptions= new AjaxOptions{
OnComplete= "fnCompleted",
Url= '@Url.Action("myAction", "myController")',
Method= "POST"
}
<div id="somediv">/*Here goes the json response*/</div>
using(Ajax.BeginForm(ajaxOptions)){
@Html.EditorForModel()
<input type="submit" name="send" value="Send">
}
这是我的控制器动作的一部分:
[HttpPost]
public JsonResult myAction(MyModel mymodel)
{
try
{
if (myModel== null)
throw new Exception("The model is empty");
if (!ModelState.IsValid)
throw new Exception("The model is wrong");
var found = /*Look for existence of the model in the database*/;
if(found)
throw new Exception("Already exists the object");
/*Operation with the database*/
var result = Json(
new
{
Success = true,//success
StatusMessage = "Object created successfully"
});
return result;
}
catch (Exception exception)
{
var result = Json(
new
{
Success = false,//error
StatusMessage = exception.Message
});
return result;
}
}
【问题讨论】:
-
将您尝试过的内容添加到您的帖子中
-
请提供代码示例,以便我们更清楚地了解您所描述的内容。你试过什么?什么有效?你走了多远?一个 JSFiddle 将是理想的,以及您尝试调用的控制器中的一些示例代码。
标签: .net ajax json asp.net-mvc-3