2015-10-18 3 views
-1

Я действительно полный новичок здесь, поэтому заранее извиняюсь за глупое звучание. Я пытаюсь создать простую веб-приложение в 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=&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#

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 }); 
      } 
     } 
    } 
} 
+0

Вы можете использовать вспомогательный метод Html.DropDownList, чтобы нарисовать DropDownlist, и один из параметров этого метода - это коллекция, которую вы привезли из базы данных –

+0

, если вы можете вставить часть своего кода, код представления и Code of the Controller, классы EntityFramework и контекст, если вы хотите, чтобы мы предоставили вам код. не видя своего кода, вы не можете дать вам больше, чем принципал и идея –

ответ

1

Небольшой пример о том, как создать DropDownList в 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.

View (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 на верхней части представления определяет, какая модель будет использоваться для представления. Свойства модели можно получить с помощью элемента модели.

Смежные вопросы