Reputation: 1825
I recently noticed that MVC's Ajax.BeginForm
was acting strangly when returning a view. At first everything looked alright, but then I realised all the bindings that happen in document ready were lost. Document ready was not being executed.
Knowing that this works elsewhere, I found that doing the same thing with a jquery get did execute document ready. But as far as I can understand, the two methods are fundamentally doing the same thing. My quick fix was to strip out the helper's Replace TargetId implementation and use it's AjaxOptions.OnSuccess
to call my jquery.get()
implementation.
But why does document ready fire when I use jquery.get()
, and not when I use Ajax.BeginForm
to replace a div
?
// This method returns a the partial view from DoSomething, but DOES NOT execute the
// partial view's document.ready
using (Ajax.BeginForm("DoSomething", "Somewhere", new AjaxOptions { HttpMethod = "Post", InsertionMode = InsertionMode.Replace, UpdateTargetId = "demo" }))
{ %>
<div id="demo"></div>
<% } %>
Example 1. MVC Helper method for replacing a div
// This method returns nothing from DoSomething, calls getSomething onSuccess and DOES
// execute the partial view's document.ready
using (Ajax.BeginForm("DoSomething", "Somewhere", new AjaxOptions { HttpMethod = "Post", OnSuccess = "function() { getSomething(); }" }))
{ %>
<div id="demo"></div>
<% } %>
// this being the simplified js function
function getSomething(){
var $targetDiv = $("#demo");
var url = "<%: Url.Action("LoadSomething", "Somewhere") %>";
$.get(url, { }, function (result) { $targetDiv.html(result) });
});
Example 2. jquery.get() method for replacing a div
Upvotes: 2
Views: 1709
Reputation: 231
I can suggest alternative way how build rich application without JavaScript code like are Ajax.BeginForm but more flexibility and customizable.
Sample: Get html from controller and insert into dom element.
<div id="containerId"></div>
@(Html.When(JqueryBind.Click)
.Do()
.AjaxGet(Url.Action("GetContent", "SomeController"))
.OnSuccess(dsl => dsl.With(r=> r.Id("containerId"))
.Core()
.Insert
.Html())
.AsHtmlAttributes()
.ToButton("Insert button"))
You use any dom value for request like are
AjaxGet(Url.Action("GetContent", "SomeController",new
{
Criterie=Selector.Jquery.Name("txtName")
} ))
You can look sample on official documentation and download sample project sample from github.
Upvotes: 2