2015-10-18 180 views
-1

我在這裏實際上是一個完整的初學者,所以我提前爲聽起來啞巴道歉。我試圖在Visual Studio中創建一個簡單的Web應用程序,並且我需要創建一個從數據庫(SQL Server)填充選項的選擇(下拉列表)。我已經獲得了數據庫,所以我不需要構建它,而且我在設計或其他方面沒有任何靈活性。我也試圖使用MVC設置。如何從SQL數據庫填充選擇列表?

我意識到這可能是以前被問過的,但是我所遇到的所有答案都只是爲被問到的每個特定情況提供了正確的代碼。我真的很想知道這是如何工作的,也是最簡單,最簡潔的方法。

我在Web.config文件中的連接語句:

<connectionStrings> 
<add name="ScrumTimerEntities" connectionString="metadata=res://*/Model.ScrumTimerEntities.csdl|res://*/Model.ScrumTimerEntities.ssdl|res://*/Model.ScrumTimerEntities.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=***;initial catalog=ScrumTimer;persist security info=True;user id=***;password=***;MultipleActiveResultSets=True;App=EntityFramework&quot;" 
    providerName="System.Data.EntityClient" /> 
<add name="ScrumTimerConnectionString" connectionString="Data Source=stem.arvixe.com;Initial Catalog=ScrumTimer;Persist Security Info=True;User ID=scrumtimer-admin;Password=test1234;MultipleActiveResultSets=True;Application Name=EntityFramework" 
    providerName="System.Data.SqlClient" /> 

我使用Visual Studio 2015和C#

編輯:添加代碼。我沒有把它放在第一位,因爲我不知道該從哪裏開始,但是我想我也不知道它們並不重要。您可以看到,我正在嘗試製作一個計時器,當計時器達到零時向服務器發送消息。我需要下拉列表來包含來自數據庫的用戶列表。

視圖 -

@{ 
    ViewBag.Title = "Home Page"; 
} 
@section scripts 
{ 
    <script> 
     var gritterAdd = function (message) { 
      $.gritter.add({ 
       // (string | mandatory) the heading of the notification 
       title: 'Notice!', 
       // (string | mandatory) the text inside the notification 
       text: message, 
      }); 
     } 

     $(function() { 
      var totalTime = 15; 
      var i = totalTime; 
      $('.time-remaining').html(i); 
      $('.start-button').click(function() { 
       var i = totalTime; 
       $('.time-remaining').html(i); 
       var minute = setInterval(function() { 
        i--; 
        $('.time-remaining').html(i); 

        if (i == 0) { 
         clearInterval(minute); 
         $('.time-remaining').html('Your time is up!'); 

         var usernameValue = $("#username").val(); 
         var timeRemaining = $("#time-remaining").val(); 
         var timeUsedValue = totalTime; 
         //this is obviously impossible right now, but in the future, the user should be able to stop the clock early. 
         if (i > 0) { timeUsedValue = totalTime - timeRemaining; } 

         //here we are going to send a request to the server. 
         $.ajax('/home/updateserver', { 
          type: 'POST', 
          data: { username: usernameValue, timeused: timeUsedValue}, 
          success: function (data) { 
           if (data.success) { 
            gritterAdd(data.updatedUsername + " was updated on server" + "\n A total of " + timeUsedValue + " seconds were used."); 
           } else { 
            gritterAdd("An error occurred while updating."); 
           } 
          } 
         }); 
        } 

        if (i == 10) { gritterAdd('You have 10 seconds remaining.'); } 
       }, 1000); 
      }); 
     }); 
    </script> 
} 

<div> 
    <p>You've reached the home page!</p> 

    <div class="timer-container"> 
     <h2>User:</h2> 
     @*<select id="username"> 
      <option value="Joe">Joe</option> 
      <option value="Brendan">Brendan</option> 
     </select>*@ 

     <span>Time Remaining:</span> 
     <p class="time-remaining"></p> 
     <button class="start-button">Start</button> 
    </div> 
</div> 

和控制器 -

namespace ScrumTimer.Web.Controllers 
{ 
    public class HomeController : Controller 
    { 
     // 
     // GET: /Home/ 
     public ActionResult Index() 
     { 
      return View(); 
     } 

     public ActionResult About() 
     { 
      return View(); 
     } 

     /// <summary> 
     /// 
     /// </summary> 
     /// <returns></returns> 
     [HttpPost] 
     public JsonResult UpdateServer(string username, int timeUsed) 
     { 
      using (var context = new ScrumTimerEntities()) 
      { 
       var user = context.UserProfiles.SingleOrDefault(u => u.Username == username); 

       var scrumTime = new ScrumTime {UserProfile = user, TimeUsed = timeUsed, CreatedAt = DateTime.Now}; 
       context.ScrumTimes.Add(scrumTime); 

       context.SaveChanges(); 

       return Json(new { success = true, updatedUsername = username, scrumTimeId = scrumTime.Id }); 
      } 
     } 
    } 
} 
+0

您可以使用Html.DropDownList幫助器方法繪製DropDownlist,並且此方法的其中一個參數是您從數據庫中帶來的集合 –

+0

如果您可以粘貼一些代碼,則視圖的代碼和Controller的代碼,EntityFramework類和上下文,如果你希望我們給你一個代碼。沒有看到你的代碼,你不能給你比校長和想法更多的東西 –

回答

1

關於如何創建一個MVC下拉列表一個小例子。不包括從數據庫獲取數據的代碼,但可以根據要求添加代碼。

型號:

public class ScrumTimerModel{ 
     [DisplayName("My display name")] 
     public int SelectedItem { get; set; } 

     public List<SelectListItem> Items { get; set; } 
} 

顯示名稱是顯示在標籤上的名稱。 「selectListitem」列表包含所有下拉項目。這是一個名稱值集合。該值必須是一個字符串

控制器:

public ActionResult Index() 
{ 
      //Get data from database 
      return View(new ScrumTimerModel(){Items=listFromDb.Select(t=> 
         new SelectListItem(){ 
         Text=t.Name, Value=t.Value 
        }) 
      }); 
} 

填寫的模型,並設置視圖模型。索引頁面將在此示例中獲取模型。 listFromDb是從數據庫中檢索的行的列表。您可以通過在模型上設置selectedItem屬性來在下拉菜單中設置選定的項目。

視圖(CSHTML):在視圖頂部

@model ScrumTimer.Web.Models.ScrumTimerModel 
<div> 
    <div>@Html.LabelFor(t=>t.SelectedItem)</div> 
    <div>@Html.DropDownListFor(t => t.SelectedItem, Model.Items)</div> 
</div> 

@model定義什麼樣的模式將被用於該視圖。模型屬性可以通過使用Model項目來檢索。