2013-05-29 53 views
2

嗨我已經創建了一個表,並通過ADO.NET實體將其連接到MVC項目。 連接之後,我添加了實體的控制器,並在MVC項目的VIEW文件夾中創建了一組cshtml文件。 但現在我需要的是創建一個下拉列表和文本框。 我在cshtml文件中創建了下拉列表,並且還在CONTROLLER中創建了它的邏輯。 我也可以創建TEXTBOXES,但是我正在面對根據下拉列表選擇弄髒TEXTBOX的問題。由VS 2012生成如何根據MVC中的下拉選擇填充文本框..?

我的模型汽車是

public partial class Plan_S 

    { 

     public int PlanId_PK { get; set; } 
     public string PlanNames { get; set; } 
     public string Hours { get; set; } 
    } 

我的用於顯示下拉列表控制器是 '

public class dropdownController : Controller 
    { 


     private PivotEntities db = new PivotEntities(); 

     // 
     // GET: /dropdown/ 

     public ActionResult Index() 
     { 
      ViewBag.plannames = new SelectList(db.Plan_S, "PlanId_PK", "PlanNames"); 

      return View(); 
     } 

     protected override void Dispose(bool disposing) 
     { 
      db.Dispose(); 
      base.Dispose(disposing); 
     } 
     public ActionResult ddl() 
     { 
      return View(new Plan_S()); 
     } 

    }` 

我的用於顯示下拉列表view.cshtml是

`

@model Pivot.Models.Plan_S 
@{ 
    ViewBag.Title = "Index"; 
} 

<h2>Index</h2> 


<div> 

    @Html.DropDownList("PlanNames", "--select--") 

</div> 

`

現在,當我在下拉列表中選擇一個項目時,它應該自動填充表中的相應值。 在我的代碼中,Plan_S表被自動生成爲Plan_S MODEL Class。但是在數據庫中,我在表中爲這些列設置了一組值。

eg..)  PlanId_PK | PlanNames | Hours 
       1   Plan1   1hrs 
       2   Plan2   2hrs 
       3   Plan3   3hrs 
在此Plan_S表

這裏,

PlanNames列都將填充在DROPDOWNLIST, 當我選擇在DDL的計劃1應該填充texbox作爲1hrs

當我選擇在計劃2 DDL它應該填充文本框爲2小時。

這是我需要的邏輯,我可以在asp webforms中做到這一點,但它在MVC中很棘手。

我認爲jQuery是需要它.......

請幫助我,我在尋找這樣的邏輯已經花了幾個小時....

在此先感謝...

回答

3

首先,讓我們創建一個視圖模型來保存這些東西:

public class PlanViewModel 
{ 
    public List<SelectListItem> Plans { get; set; } 
} 

然後,在你的控制器動作讓我們建立模型:

在您查看
public ActionResult Index() 
{ 
    var model = new PlanViewModel(); 

    model.Plans = db.Plan_S 
     .Select(p => new SelectListItem 
     { 
      Value = p.Hours, 
      Text = p.PlanNames 
     }) 
     .ToList(); 

     return View(model); 
    } 

然後執行:

@model Pivot.Models.Plan_S 
@{ 
    ViewBag.Title = "Index"; 
} 

<h2>Index</h2> 
<div> 
    @Html.DropDownList("PlanNames", Model.Plans, "--select--") 
    <input id="planHours" type="text" /> 
</div> 

然後,你需要做的jQuery中的以下內容:

<script type="text/javascript"> 
    $(function() { 
     $("[name='PlanNames']").change(function() { 
      $("#planHours").val($(this).val()); 
     }); 
    }); 
</script> 
+0

嗨mattytommo我無法理解的CurrentPlan的方法索引()...請幫助我...... – RajeshKannan

+0

@ user2309770是編輯現有計劃的功能嗎? – mattytommo

+0

mattytommo請你舉一些例子,因爲我是MVC的新手。 – RajeshKannan

相關問題