Send partial view model and Update partial view with jQuery has issues

天大地大妈咪最大 提交于 2019-12-18 09:13:38

问题


I use partial view for small model inside other view model. so i send changes of it by grabbing model data from wrapper form and using serializeArray(). then return PartialViewResult from action and finally fill partial view div container by returned result. this is my code:

var modelStr = $("#[wrapperFormName]").serializeArray();
$.ajax({
type: "POST",
url: targetUrl,
cache: false,
data: modelStr,
success: function (sucResult) {
$('#pa_Cnt').html(sucResult);
},
fail: function (result) {
alert("Fail");
}
});

and render partialview in view as this:

@using (Html.BeginForm("[ActionName]", "[CtrlName]", FormMethod.Post, new { id = "[wrapperFormName]", @enctype = "multipart/form-data" }))
{
    <div id="[partialcontainerName]">
        @Html.Partial("[partialViewName]", [partialViewModelName])
    </div>
}

One of issue is after update partial view with returned result don't work any of jQuery event handlers that bind to elements inside the partial and i know event handlers must be declare in main view and not in partial and handlers must be delegated. Second issue is updated result has new values but some of elements in partial view show old values and i set cache of ajax to false as cache of action with [OutputCache(Duration = 0)]. I'm confusing. Can anyone help me.


回答1:


Your first issue is because you must re-add your event handers. I assume you are adding your event handlers within $(document).ready or an equivalent when the page loads. After you've refreshed your partial using $.ajax, the original elements that had event handlers no longer exist - their instances have been replaced and therefore the event handlers won't fire. You need to re-add the event handlers as part of the success callback after the line:

$('#pa_Cnt').html(sucResult);

Not sure about the second issue..




回答2:


I found it. Thanks from @David for first issue. I separate internal actions of delegated events to functions that pointed with variable names and attach delegate events to them after update html of partial with returned result. this is a simple sample:

var sampleHandler = function() { //some code }

and then in ajax success:

success: function (sucResult) {
         $('#pa_Cnt').html(sucResult);
         $("[parentClassNameSelector]").on("click", '[childSelector]', sampleHandler);
   }

About second issue ModelState of MVC is Guilty. :) specially in elements that rendered by mvc helpers. So i decide to do this in controller action.

if (ModelState.IsValid) { ModelState.Clear(); }

I don't know if this is good or has any other issue. For now it was solved my problem. I'm waiting for new comments and advises. Thanks so much.



来源:https://stackoverflow.com/questions/23033242/send-partial-view-model-and-update-partial-view-with-jquery-has-issues

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!