我的页面上有四个不同的表单,每个表单都是ajax表单。
我用ajax向MVC控制器发送第一个表单的请求,它基本上会返回ViewData["TEST"]给我
我想在我的视图中使用ViewData,我需要将其设置为隐藏字段以用于其他表单。
我如何在不使用正常提交的情况下访问它?
这是我的代码:
@using (Ajax.BeginForm("Index", new AjaxOptions{ HttpMethod = "POST" }))
{
<script type="text/javascript"> alert('@(ViewData["TEST"])'); </script>
<input type="text" name="name" />
<input type="button" onclick="javacript:SubmitAjax();" />
}
<script type="text/javascript">
function SubmitAjax() {
$.ajax({
type: 'POST',
data: $("#form0").serialize(),
url: "/Home/Index",
timeout: 2000,
async: false,
success: function (data) {
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(message_Error);
}
});
}
和控制器;
[HttpPost]
public ActionResult Index(string name)
{
ViewData["TEST"] = "TESTSTRING";
return View();
}
无ViewData。只需返回内容即可。
[HttpPost]
public ActionResult Index(string name)
{
return Content("TESTSTRING");
}
要在隐藏字段中设置此项,可以在ajax函数的success
事件中进行设置
success: function (data) {
$("#hiddenElementID").val(data);
},
也不要像那样硬编码Path to action方法。始终使用HTML助手方法。
更换
url: "/Home/Index"
带有
url: "@Url.Action("Index","Home")"
我个人更喜欢避免AjaxBeginForm
方法,并希望编写一些干净的手写javascript代码来处理此问题。
@using(Html.Beginform())
{
<input type="text" name="name" />
<input type="submit" id="saveName" value="Save" />
}
<script type="text/javascript">
$(function(){
$("#saveName").click(function(e){
e.preventDefault();
$.post("@Url.Action("Index","Home")",
$(this).closest("form").serialize(),
function(data){
$("#yourHiddenElementID").val(data);
});
});
});
</script>
编辑:根据注释。
如果你想返回多个项目,你可以返回JSON
Ex2:将匿名类型返回到JSON
[HttpPost]
public ActionResult Index(string name)
{
return JSON(new { status : "true", ItemCount=35, UserName="Marc"} );
}
Ex1:将ViewModel返回到JSON
假设你有这样的课程
public class Result
{
public string Status { set;get;}
public int ItemCount { set;get;}
public string UserName { set;get;}
}
现在您可以使用这个类并将其作为JSON
返回
[HttpPost]
public ActionResult Index(string name)
{
return JSON(new Result { Status : "true",
ItemCount=25, UserName="Scott"} );
}