Я действительно полный новичок здесь, поэтому заранее извиняюсь за глупое звучание. Я пытаюсь создать простую веб-приложение в Visual Studio, и мне нужно создать список выбора (drop down), в котором параметры заполняются из базы данных (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="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#
EDIT: Добавление кода. Я не ставил это первым, потому что ничто из этого не связано с тем, что я пытаюсь сделать, поскольку я не знаю, с чего начать, но, я думаю, я не знаю достаточно, чтобы знать, что это тоже не важно! Вы можете видеть, что я пытаюсь сделать таймер, который отправляет сообщение на сервер, когда таймер достигает нуля. Мне нужен выпадающий список, чтобы содержать список пользователей из базы данных.
View -
@{
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 });
}
}
}
}
Вы можете использовать вспомогательный метод Html.DropDownList, чтобы нарисовать DropDownlist, и один из параметров этого метода - это коллекция, которую вы привезли из базы данных –
, если вы можете вставить часть своего кода, код представления и Code of the Controller, классы EntityFramework и контекст, если вы хотите, чтобы мы предоставили вам код. не видя своего кода, вы не можете дать вам больше, чем принципал и идея –