[英]How do I populate a selection list from an SQL database?
我在這里實際上是一個完整的初學者,所以我提前為聽起來很愚蠢而道歉。 我正在嘗試在 Visual Studio 中創建一個簡單的 Web 應用程序,我需要創建一個選擇(下拉)列表,其中的選項是從數據庫 (SQL Server) 填充的。 我已經獲得了數據庫,所以我不需要構建它,而且我在設計或任何方面都沒有任何靈活性。 我也在嘗試使用 MVC 設置。
我意識到之前可能已經問過這個問題,但是我遇到的所有答案都只是為被問到的每個特定情況提供正確的代碼。 我真的很想了解這是如何工作的以及最簡單、最簡潔的方法。
我的 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="data source=***;initial catalog=ScrumTimer;persist security info=True;user id=***;password=***;MultipleActiveResultSets=True;App=EntityFramework""
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 });
}
}
}
}
關於如何在 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 項檢索模型屬性。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.