2012-07-03 107 views
-1

如何在一個jQuery在一個隱藏的輸入字段在MVC4應用如何在jQuery的使用for循環

這是我的Jquery

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script> 
<script type="text/javascript"> 
    $(document).ready(function() { 
     $('p').click(function() { 
      var textbox = $('<input id="Text1" type="text" name="Name" />') 
      var oldText = $(this).text(); 
      $(this).replaceWith(textbox); 
      textbox.blur(function() { 
       var newValue = $(this).val(); 
       var listItems = $('.listItem'); 
       listItems.each(function() { 
        $(this).replaceWith(
        $('<p/>', { text: newValue }) 
        .after(
         $('<input />', { type: 'hidden', name: 'Name', value: newValue }) 
        ) 
       ); 
       }); 
       }); 

       textbox.val(oldText); 
     }); 
    }); 


</script> 
使用for循環用於編輯和存儲多個編輯值
+3

不太清楚的問題是什麼,什麼是for循環呢?它在哪些領域循環?爲什麼我們使用循環? –

+0

我有一個模型類是我分配的名稱,地址,PIN碼,當我在視圖中顯示時使用該jQuery編輯這些多個字段我想存儲該頁面上的所有編輯的字段,並顯示在我的MVC4應用程序的下一個視圖 – Pavan

回答

1

讓我們假設你有一個模型:

public class User 
{ 
    public string Name { get; set; } 
    public string Address { get; set; } 
} 

然後控制器:

public class HomeController : Controller 
{ 
    public ActionResult Index() 
    { 
     var user = new User 
     { 
      Name = "test1", 
      Address = "add1" 
     }; 
     return View(user); 
    } 

    [HttpPost] 
    public ActionResult Index(User user) 
    { 
     return Content(
      string.Format(
       "name: {0}, address: {1}", 
       user.Name, 
       user.Address 
      ) 
     ); 
    } 
} 

和視圖:

@model User 

@using (Html.BeginForm()) 
{ 
    <ul class="editor"> 
     <li> 
      @Html.LabelFor(x => x.Name, Model.Name) 
      @Html.EditorFor(x => x.Name) 
     </li> 
     <li> 
      @Html.LabelFor(x => x.Address, Model.Address) 
      @Html.EditorFor(x => x.Address) 
     </li> 
    </ul> 

    <button type="submit">OK</button> 
} 

現在你可以使用下面的javascript:

$(function() { 
    $('.editor input').blur(function() { 
     $(this).hide(); 
     $(this).closest('li').find('label').html($(this).val()).show(); 
    }); 

    $('.editor label').click(function() { 
     $(this).hide(); 
     $(this).closest('li').find('input').show(); 
    }); 
}); 

,最終以最初隱藏輸入字段,你可以定義我已經向<ul>元素.editor CSS規則:

.editor input { 
    display: none; 
} 
+0

嗨達林我分配了一個id給兩個屬性名稱我給1和地址2,所以當我編輯名稱我想顯示名稱和類似的東西的地址地址,但我無法將id傳遞給控制器​​類在上面的示例中 – Pavan

0

如果你想在jQuery中循環任何集合使用each()。爲什麼for

$.each(collectionarray, function(index, value) { 
// your code 
}); 
+0

I試過,它不工作,我無法存儲多個編輯的字段值 – Pavan

+0

請您詳細說明'多個編輯的字段值「? –

+0

例如我分配的名稱=丹尼地址=芝加哥我想​​編輯這兩個字段在我的網頁,並將兩個編輯的值傳遞到下一個Viwe – Pavan