2010-07-25 81 views
0

控制器动作:AJAX更新的div

public ActionResult Index() 
    { 

     ViewData["sample"] = DateTime.Now.ToLongTimeString(); 
     Thread.Sleep(3000); 
     return View(); 
    } 

查看网页:

<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server"> 

<h2>Index</h2> 

<div id="divId"><%= Html.Encode(ViewData["sample"])%></div> 

<script type="text/javascript">var event = new Object(); $get("panelOneForm").onsubmit();</script> 
<%using (Ajax.BeginForm("Index", "Proba", new AjaxOptions() { UpdateTargetId = "divId" }, new { id = "panelOneForm" })) { } %> 

</asp:Content> 

我尽量让自动更新视图,但失败了。哪里不对?

回答

0

您可以定义一个无形的提交表单内按钮:

<div id="divId"></div> 

<%using (Ajax.BeginForm("Index", "Proba", new AjaxOptions() { UpdateTargetId = "divId" })) { %> 
    <input type="submit" id="btnSubmit" style="display:none;" /> 
<% } %> 

<script type="text/javascript"> 
    // Make sure you put this script after the form 
    // so that the button is loaded into the DOM before 
    // manipulating it 
    $get("btnSubmit").click(); 
</script> 

另外,Proba控制器上的Index行动您异步调用需要仅返回部分视图或直接返回一些内容。请注意,ViewData不再既不在控制器动作,也没有在产生的div使用:

public ActionResult Index() 
{ 
    // You probably want to remove the next line before shipping your 
    // application in production as it is not good to stall the thread for 3s 
    Thread.Sleep(3000); 
    return Content(DateTime.Now.ToLongTimeString(), "text/plain"); 
} 
+0

我试着用你的代码,但问题仍然存在,日期和时间不更新automaticaly – Ognjen 2010-07-25 17:06:04

+0

这个$ get(“btnSubmit”)。click();点击只有一次,为什么 – Ognjen 2010-07-25 17:14:13

+0

@Ognjen,也许是因为你只打了一次。 – 2010-07-25 18:33:41

0

您是否导入了微软的ajax库?

<script src="/Content/MicrosoftAjax.debug.js" type="text/javascript"></script> 
<script src="/Content/MicrosoftMvcAjax.debug.js" type="text/javascript"></script> 

这里是一个tutorial。你有萤火虫吗?如果是这样,尝试看看,如果库正确加载,并且没有错误,其中检测在执行

+0

是的,我有萤火虫和进口Ajax库 – Ognjen 2010-07-25 12:16:10

+0

我有MisrosoftAjax.debug.js此错误:Sys.ArgumentTypeException:物体类型'Sys._Application'不能转换为类型'Sys._Application'。参数名称:实例 [打破这个错误] if(!this.isInstanceOfType(instanc ... e',Object.getType(instance),this); – Ognjen 2010-07-25 12:25:48

+0

你有任何其他的ajax在打电话的页面?您是否在您的web.config中引用了该脚本? – Nealv 2010-07-25 12:34:35