【问题标题】:How do I populate a selection list from an SQL database?如何从 SQL 数据库中填充选择列表?
【发布时间】:2015-10-18 16:14:49
【问题描述】:

我在这里实际上是一个完整的初学者,所以我提前为听起来很愚蠢而道歉。我正在尝试在 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=&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 });
            }
        }
    }
}

【问题讨论】:

  • 您可以使用 Html.DropDownList 辅助方法来绘制 DropDownlist,该方法的参数之一是您从数据库中获取的集合
  • 如果你能粘贴一些你的代码,视图的代码和控制器的代码,EntityFramework 类和上下文,如果你想让我们给你一个代码。没有看到你的代码,你不能给你比校长和理念更多的东西

标签: c# sql-server asp.net-mvc linq visual-studio-2015


【解决方案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 定义了视图使用的模型。模型属性可以通过使用模型项来检索。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-09-17
    • 1970-01-01
    • 1970-01-01
    • 2020-05-09
    • 2012-10-02
    • 2018-09-11
    • 1970-01-01
    相关资源
    最近更新 更多