2010-10-12 78 views
2

我有一個js函數,它可以從控制器創建新的員工,將它插入表單標籤(用於以後的.serialize()),然後將此html插入createDialog div並顯示此div作爲對話。從對話框的jquery帖子表格

<div id="createDialog" style="display:none;"> 
</div> 

$.get('/Employee/Create', 
    function (html) { 
     html = "<form id='createEmp'>" + html; 
     html = html + "</form>"; 
     $("#createDialog").html(html); 
     $("#createDialog").dialog({ 
      modal: true, 
      width: 500, 
      buttons: { "Save": function() { postEmployee(); } }, 
      close: function (ev, ui) { $(this).dialog('destroy'); } 
     }); 
    }); 


    function postEmployee() { 

     $.post('/Employee/Create', 
     $("#createEmp").serialize(), 
     function (html) { 
      $('#reply').html(html); 
     }); 
    } 

這個工作,但只有一次。對於每一個下一篇文章,以前文章中的所有表單字段也會添加到當前文章中。 這可以修復嗎?

Tahnk你!

回答

1

您還需要刪除您創建的<form>元素,像這樣:

close: function (ev, ui) { $(this).dialog('destroy').empty(); } 

您也可以使整個功能有點吸塵器.wrapInner()這樣的:

$.get('/Employee/Create', function (html) { 
    $("#createDialog").html(html).wrapInner("<form id='createEmp'> />"); 
    $("#createDialog").dialog({ 
     modal: true, 
     width: 500, 
     buttons: { "Save": postEmployee }, 
     close: function (ev, ui) { $(this).dialog('destroy').empty(); } 
    }); 
}); 
0

這是更好不創造和摧毀,而是創造,然後打開和關閉。

HTML

<div id="createDialog" style="display:none;"> 
</div> 

JS

var $dialog = $("#createDialog").dialog({ 
    modal: true, 
    autoOpen: false, 
    width: 500, 
    buttons: { "Save": function() { postEmployee(); } }, 
    close: function (ev, ui) { $(this).dialog('close'); } 
}); 
$.get('/Employee/Create', function (html) { 
    html = "<form id='createEmp'>" + html; 
    html = html + "</form>"; 
    $("#createDialog").html(html); 
    $dialog.dialog("open"); 
}); 


function postEmployee() { 
    $.post('/Employee/Create', 
    $("#createEmp").serialize(), 
    function (html) { 
     $('#reply').html(html); 
    }); 
} 
0
$.get('/Employee/Create', 
function (html) { 
    var nodeContent= "<form id='createEmp'>" + html + "</form>"; 
    $("#createDialog").empty(); 
    $("#createDialog").html(nodeContent); 
    $("#createDialog").dialog({ 
     modal: true, 
     width: 500, 
     buttons: { "Save": function() { postEmployee(); } }, 
     close: function (ev, ui) { $(this).dialog('destroy'); } 
    }); 
}); 
0

使用來自malsup優秀的jQuery表單插件:成功http://malsup.com/jquery/form/

呼叫clearForm():

function postEmployee() 
    $('#createEmp').ajaxSubmit({ 
     url: '/Employee/Create' 
     , success: function(html){ 
      $('#reply').html(html); 
      $('#createEmp').clearForm(); 
     } 
    }); 
} 

創建表單後調用resetForm()以防止瀏覽器恢復緩存的值。

$('#createEmp').resetForm();