2016-01-05 2 views
0

Мне сложно показать выпадающий список для представления, значения будут заполнены из базы данных. Я использую MS SQL Server в качестве базы данных.DropDownListFor в MVC 4

Я хочу показать выпадающий список в ApplyingFor, который будет заселен из базы данных.

Пожалуйста, помогите мне. Это модель

public class CandidateProfile 
{ 
     [Display(Name = "Candidate Name")] 
     [Required(ErrorMessage = "Provide a Name", AllowEmptyStrings=false)] 
     [DataType(DataType.Text)] 
     public string CandidateName { get; set; } 

     [Required(ErrorMessage = "Provide Your Address",AllowEmptyStrings = false)] 
     [Display(Name = "Address")] 
     [DataType(DataType.MultilineText)] 
     public string Address { get; set; } 

     [Display(Name = "Phone Number")] 
     [Required(ErrorMessage = "Provide a Phone Number")] 
     [RegularExpression("^([07][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9] | 8[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9] | 9[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9])$", ErrorMessage = "Enter Valid Mobile Number")] 
     public string PhoneNumber { get; set; } 

     [Display (Name = "Email-Id")] 
     [Required(ErrorMessage="Provide an email-id")] 
     [EmailValidator] 
     public string EmailId { get; set; } 

     [Display (Name = "Applying For")] 
     public string **ApplyingFor** { get; set; } 

     [Display (Name = "Experience")] 
     [Required(ErrorMessage = "")] 
     public int Experience { get; set; } 

     [Display (Name = "Present Location")] 
     [Required(ErrorMessage = "")] 
     public string PresentLocation { get; set; } 
} 



public class ApplyingPositions 
{ 
    public IEnumerable<ApplyingPositions> ApplyingPosition { get; set; } 
} 
public class ApplyingPosition 
{ 
    public int APId { get; set; } 
    public string Designation { get; set; } 
} 

Это Вид:

@model Recruitment.Models.CandidateProfile 

@{ 
    ViewBag.Title = "Create"; 
} 

<h2>Create</h2> 

@using (Html.BeginForm()) { 
    @Html.AntiForgeryToken() 
    @Html.ValidationSummary(true) 

    <fieldset> 
     <legend>CandidateProfile</legend> 

     <div class="editor-label"> 
      @Html.LabelFor(model => model.CandidateName) 
     </div> 
     <div class="editor-field"> 
      @Html.EditorFor(model => model.CandidateName) 
      @Html.ValidationMessageFor(model => model.CandidateName) 
     </div> 

     <div class="editor-label"> 
      @Html.LabelFor(model => model.Address) 
     </div> 
     <div class="editor-field"> 
      @Html.EditorFor(model => model.Address) 
      @Html.ValidationMessageFor(model => model.Address) 
     </div> 

     <div class="editor-label"> 
      @Html.LabelFor(model => model.PhoneNumber) 
     </div> 
     <div class="editor-field"> 
      @Html.EditorFor(model => model.PhoneNumber) 
      @Html.ValidationMessageFor(model => model.PhoneNumber) 
     </div> 

     <div class="editor-label"> 
      @Html.LabelFor(model => model.EmailId) 
     </div> 
     <div class="editor-field"> 
      @Html.EditorFor(model => model.EmailId) 
      @Html.ValidationMessageFor(model => model.EmailId) 
     </div> 

     <div class="editor-label"> 
      @Html.LabelFor(model => model.ApplyingFor) 
     <div class="editor-field"> 
      @Html.EditorFor(model => model.ApplyingFor) 
      @Html.ValidationMessageFor(model => model.ApplyingFor) 
     </div> 

     <div class="editor-label"> 
      @Html.LabelFor(model => model.Experience) 
     </div> 
     <div class="editor-field"> 
      @Html.EditorFor(model => model.Experience) 
      @Html.ValidationMessageFor(model => model.Experience) 
     </div> 

     <div class="editor-label"> 
      @Html.LabelFor(model => model.PresentLocation) 
     </div> 
     <div class="editor-field"> 
      @Html.EditorFor(model => model.PresentLocation) 
      @Html.ValidationMessageFor(model => model.PresentLocation) 
     </div> 

     <p> 
      <input type="submit" value="Create" /> 
     </p> 
    </fieldset> 
} 

<div> 
    @Html.ActionLink("Back to List", "Index") 
</div> 

@section Scripts { 
    @Scripts.Render("~/bundles/jqueryval") 
} 

ответ

1

Вы должны передать список опций от контроллера для просмотра. Итак, прежде чем вернуться View

var listOfPositions = new List<ApplyingPosition>(); 

listOfPositions = //Call the service to populate the listOfPositions from Database here 

ViewBag.PositionsList = new SelectList(listOfPositions, "APId", "Designation"); 

На ваш взгляд, вместо @Html.EditorFor(model => model.ApplyingFor)

@Html.DropDownListFor(m => m.ApplyingFor, (SelectList)ViewBag.PositionsList, "Select") 
+0

Я сделал это, но я не могу сохранить данные. – Arka

+0

Какая ошибка? Получаете ли вы выбранное значение в контроллере после отправки? – adiga

+0

измените свойство 'ApplyingFor' в классе' CandidateProfile' на 'int', а затем попробуйте – adiga

0

заселить lstApplyingFor (список) формируют вашу БД. и в контроллере

ViewBag.ApplyingFor = new SelectList(lstApplyingFor, "Id", "Name"); 

и в целях: -

@Html.DropDownList(m => m.ApplyingFor,"ApplyingFor", "--Select--") 
0

1 первого) Вы должны создать источник для выпадающего списка как-

var listForApplyingFor= db.Table.Select(o=> new SelectListItem{ 
    Value=o.ID, 
    Text= o.Text 
}).ToList(); 

ViewBag.ItemsApplyingFor= listForApplyingFor 

.Cshtml View-

@Html.DropdownListFor(m=>m.ApplyingFor, new SelectList(ViewBag.ItemsApplyingFor,"Value","Text"),"Select...", htmlAttributes:new{ }) 

Сообщите мне, если это поможет.

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