I'm picking up that it's a best practice to use the strongly-typed textboxfor helper method rather than simple textbox. I'm all for that. But as I made the switch in my project, the data stopped getting written back to the database. I'm having trouble figuring out why.
Here's my model.
public class MasterModel
{
[Key]
public int mandatoryKey { get; set; }
public List<tblAddress> Address { get; set; }
public List<tblPrimaryCaregiverdata> Primary { get; set; }
public List<tblPhone> Phone { get; set; }
public List<tblEmail> Email { get; set; }
public List<tblRelatedCaregiver> Related { get; set; }
public List<tblTrainingHistoryMain> TrainingHistory { get; set; }
public List<tblInquiryReferralStatu> InquiryReferral { get; set; }
}
Then the controller
public ActionResult Create(MasterModel masterModel)
{
if (ModelState.IsValid)
{
db.tblPrimaryCaregiverdatas.Add(masterModel.Primary[0]);
db.SaveChanges();
int newCareGiverID = db.tblPrimaryCaregiverdatas.OrderByDescending(p => p.CareGiverID)
.FirstOrDefault().CareGiverID;
foreach (var ph in masterModel.Phone)
{
ph.CareGiverID = newCareGiverID;
db.tblPhones.Add(ph);
}
db.SaveChanges();
return RedirectToAction("Index");
}
Now, in the view (which invokes several partial views, one for each table in the master model), when I created the fields like this:
SelectList phonetypes = ViewBag.PhoneType;
<div>
<label class="label-fixed-width">Phone:</label>
#Html.TextBox("masterModel.Phone[0].phone", null, new { style = "width: 600px" })
#Html.DropDownList("masterModel.Phone[0].PhoneType",phonetypes, null, new
{
#class = "form-control-inline dropdown",
style = "width: 100px"
})
...I was able to write data back into the database. But when I switched over to textboxfor like this:
SelectList phonetypes = ViewBag.PhoneType;
<div>
<label class="label-fixed-width">Phone:</label>
#Html.TextBoxFor(x => x.Phone[0].Phone, null, new { style = "width: 600px" })
#Html.DropDownListFor(x => x.Phone[0].PhoneType, phonetypes,"--------", new
{
#class = "form-control-inline dropdown",
style = "width: 100px"
})
The Phone section of the MasterModel is empty when I post back. Can someone help me understand what's going on here?
When you post a model back to an ActionResult and return the same View, the values for the model objects are contained in the ModelState. The ModelState is what contains information about valid/invalid fields as well as the actual POSTed values. If you want to update a model value, you can do this:
foreach (var ph in masterModel.Phone)
{
ModelState.Clear()//added here
ph.CareGiverID = newCareGiverID;
db.tblPhones.Add(ph);
}
Related
I have a number of awards in my view and within each award there is a corresponding list of qualifications. I have created a ViewModel to display each award and with a click of a button a modal should appear with its relevant qualifications which can be marked as completed/updated by the user. However on the Post of the data it is not binding to my ViewModel in my controller method. The data is appearing in my view as expected with each Award only showing its relevant qualifications. I have used FormCollection to access some of the fields for testing purposes and the data is being posted back. Any help would be great!
ViewModel
public class CandidateExtended
{
public CandidateExtended()
{
this.Qualifications = new List<Qualification_Extended>();
}
public int AwardID { get; set; }
public int FrameworkID { get; set; }
public string ULN { get; set; }
public string Forename { get; set; }
public string Surname { get; set; }
public string TitleShort { get; set; }
public string TitleFull { get; set; }
public DateTime DOB { get; set; }
public string Award { get; set; }
public int AwardLevel { get; set; }
public string Status { get; set; }
public string Completion { get; set; }
public string SelectedRoute { get; set; }
public List<Qualification_Extended> Qualifications { get; set; }
public void addQualification(Qualification_Extended qualification)
{
Qualifications.Add(qualification);
}
}
Controller
[HttpGet]
public ActionResult Index()
{
var awardDetails = (from award in db.award
join candidate in db.candidate
on award.ULN equals candidate.ULN
join framework in db.framework
on award.QAN equals framework.QAN
where award.OrganisationIdentityID == organisationID
select new AwardDetails_Extended
{
AwardID = award.AwardID,
ULN = award.ULN,
AwardStatus = award.AwardStatus,
Forename = candidate.Forename,
Surname = candidate.Surname,
DOB = candidate.DOB,
FrameworkID = framework.FrameworkID,
TitleFull = framework.TitleFull,
TitleShort = framework.TitleShort,
AwardLevel = framework.AwardLevel,
Award = framework.Award,
Completion = framework.Completion
}).ToList();
var qualificationDetails = (from candidateQualification in db.candidateQualification
join qualification in db.qualification
on candidateQualification.QualificationID equals qualification.QualificationID
select new Qualification_Extended
{
ID = candidateQualification.ID,
QualificationID = candidateQualification.QualificationID,
ULN = candidateQualification.ULN,
FrameworkID = candidateQualification.FrameworkID,
Achieved = candidateQualification.Achieved,
DateAchieved = candidateQualification.DateAchieved
}).ToList();
List<CandidateExtended> candidateVM = new List<CandidateExtended>();
foreach (var item in awardDetails)
{
CandidateExtended vm = new CandidateExtended();
vm.AwardID = item.AwardID;
vm.FrameworkID = item.FrameworkID;
vm.ULN = item.ULN;
vm.Forename = item.Forename;
vm.Surname = item.Surname;
vm.DOB = item.DOB;
vm.TitleShort = item.TitleShort;
vm.TitleFull = item.TitleFull;
vm.Award = item.Award;
vm.AwardLevel = item.AwardLevel;
vm.Status = item.AwardStatus;
vm.Completion = item.Completion;
vm.SelectedRoute = item.SelectedRoute;
foreach (var qualification in qualificationDetails)
{
if (qualification.ULN == item.ULN && qualification.FrameworkID == item.FrameworkID)
{
vm.addQualification(qualification);
}
}
candidateVM.Add(vm);
}
return View(candidateVM);
}
View
#using (Html.BeginForm("UpdateAward", "Organisation", FormMethod.Post))
{
#Html.HiddenFor(a => award.AwardID)
<div class="row">
<div class="col-md-12">
<div class="row org-row-main">
<div class="col-md-7"><h4 class="org-type">Qualification</h4></div>
<div class="col-md-2"><h5 class="org-completed">Completed</h5></div>
<div class="col-md-3"><h5 class="org-date">Date</h5></div>
</div>
<hr class="org-hr"/>
#for (int i = 0; i < award.Qualifications.Count(); i++)
{
var qualification = award.Qualifications[i];
<div class="row org-row">
<div class="col-md-7">
#Html.HiddenFor(a => award.Qualifications[i].ID)
</div>
<div class="col-md-2">
#Html.CheckBoxFor(a => award.Qualifications[i].Achieved)
</div>
<div class="col-md-3">#Html.TextBoxFor(a => award.Qualifications[i].DateAchieved, "{0:dd/MM/yyyy}")
</div>
</div>
}
</div>
</div>
<button type="submit" class="btn admin-button" style="margin-top: 0;">Save</button>
}
UpdateAward
[HttpPost]
public ActionResult UpdateAward(CandidateExtended model, FormCollection collection)
{
return RedirectToAction("Index", "Login");
}
First (and you may already have this, but we can't see it): your View should start with a line containing #model List<CandidateExtended> (prefix the inner Type with the proper namespace).
Then in the View you should use Model, which is by definition of the exact type specified after the #model keyword.
We see that you are using award, we can't see where it comes from, presumably it is set using something like var award = Model[j] or foreach (var award in Model).
Never use such temporary or helper variables (for efficiency) in a View to render a Form; the View needs the fully qualified name of all objects, e.g. Model.Item[x].SubItem[y] in order to generate Form field names that can be used for Model Binding.
E.g. this : #Html.HiddenFor(a => award.Qualifications[i].ID)
should be: #Html.HiddenFor(a => Model[j].Qualifications[i].ID)
And make the same change in all other places.
Then do as was already suggested, use the List<...> in your Controller Post method.
Finally also please remove the FormCollection, it is not needed if you have everything set up as described here. Decent MVC code never uses FormCollection, ever.
Try calling the posted method on a separate button instead of BeginForm and it should work.
I have a page that contains multiple forms to edit questions for a single quiz, each question has its own list of answers. So for each question inside this quiz there is a form for which a user can edit the question (and answers), See below:
#model OLTINT.Areas.admin.ViewModels.OldQuizQAViewModel
<h1>Edit #Model.QuizTitle quiz</h1>
<hr />
<p class="breadcrumb">
#Html.ActionLink(HttpUtility.HtmlDecode("◄") + " Back to List", "Quizzes", new { id = Model.CourseID }, new { #class = "" })
</p>
#for (int j = 0; j < Model.OldQuizQuestions.Count(); j++)
{
using (Ajax.BeginForm("EditQuiz", "Course", null, new AjaxOptions
{
HttpMethod = "POST",
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "button"
}))
{
#Html.AntiForgeryToken()
#Html.HiddenFor(model => model.QuizID)
#Html.HiddenFor(model => model.OldQuizQuestions[j].QuizQuestionID)
<p class="form_title">Question number #Model.OldQuizQuestions[j].Order</p>
<div class="resize_input">#Html.EditorFor(model => model.OldQuizQuestions[j].Question)</div>
<p class="form_title">#Html.LabelFor(model => model.OldQuizQuestions[j].Type)</p>
<div class="resize_input">#Html.DropDownListFor(model => model.OldQuizQuestions[j].Type, ViewBag.types, "Please choose...", new { #class = "chosen-select" })</div>
<p class="form_title">Choose correct answers</p>
Char x = 'a';
for (int i = 0; i < Model.OldQuizQuestions[j].OldQuizAnswers.Count(); i++)
{
x++;
if (i == 0)
{
x = 'a';
}
<div style="display:table; width:100%;">
<div class="divTableCell" style="padding:0 10px 10px 0; vertical-align:middle; min-width:6%;">
#Html.CheckBoxFor(model => model.OldQuizQuestions[j].OldQuizAnswers[i].Correct, new { style = "" })
#Html.LabelFor(model => model.OldQuizQuestions[j].OldQuizAnswers[i].Correct, "["+ x +"]")
</div>
<div class="divTableCell quiz_input">
#Html.HiddenFor(model => model.OldQuizQuestions[j].OldQuizAnswers[i].QuizAnsID)
#Html.EditorFor(model => model.OldQuizQuestions[j].OldQuizAnswers[i].Answer)
</div>
</div>
}
<div class="button_container">
<p id="button"></p>
#Html.ActionLink("Delete this question", "DeleteQuestion", new { id = Model.OldQuizQuestions[j].QuizQuestionID }, new { #class = "button button_red button_not_full_width" })
<input type="submit" value="Save" class="button button_orange button_not_full_width" />
</div>
<hr />
}
}
OldQuizQAViewModel:
public class OldQuizQAViewModel
{
public int CourseID { get; set; }
public int? QuizID { get; set; }
public string QuizTitle { get; set; }
public IList<OldQuizQuestions> OldQuizQuestions { get; set; }
}
OldQuizQuestions:
public class OldQuizQuestions
{
[Key]
public int QuizQuestionID { get; set; }
public int OldQuizID { get; set; }
[Required]
public string Question { get; set; }
[Required]
public int Order { get; set; }
[Required]
public int Type { get; set; }
public virtual IList<OldQuizAnswers> OldQuizAnswers { get; set; }
public virtual OldQuiz OldQuiz { get; set; }
}
OldQuizAnswers:
public class OldQuizAnswers
{
[Key]
public int QuizAnsID { get; set; }
public int QuizQuestionID { get; set; }
public string Answer { get; set; }
public int Order { get; set; }
public bool Correct { get; set; }
public bool Chosen { get; set; }
public virtual OldQuizQuestions OldQuizQuestions { get; set; }
}
Controller:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult EditQuiz(OldQuizQAViewModel model)
{
var questiondata = model.OldQuizQuestions.Single();
if (ModelState.IsValid)
{
OldQuizQuestions updatequestion = db.OldQuizQuestions
.SingleOrDefault(x => x.QuizQuestionID == questiondata.QuizQuestionID);
updatequestion.Question = questiondata.Question;
updatequestion.Type = questiondata.Type;
db.Entry(updatequestion).State = EntityState.Modified;
db.SaveChanges();
foreach (var answer in questiondata.OldQuizAnswers)
{
var updateanswer = updatequestion.OldQuizAnswers
.First(x => x.QuizAnsID == answer.QuizAnsID);
updateanswer.Answer = answer.Answer;
updateanswer.Correct = answer.Correct;
db.Entry(updateanswer).State = EntityState.Modified;
db.SaveChanges();
}
return Content("<span style='font-weight:300; font-size:1.2em; color: green; '>Saved!</span>");
}
return Content("<span class='errortext'>Please correct the marked fields!</span>");
}
Now this works fine if I want to edit the first question but when I edit anything else my controller just says null but when I check the data that's being posted everything is there (for example when i try to edit question 2):
I've had a look around on here at the many queries about model binding to a list but none have helped. Can anyone see where i'm going wrong with this?
The issue you are facing is caused by a misunderstanding of how asp.net model binding works in relation to lists. For example looking at the view model used in your controller action EditQuiz.
public class OldQuizQAViewModel
{
public int CourseID { get; set; }
public int? QuizID { get; set; }
public string QuizTitle { get; set; }
public IList<OldQuizQuestions> OldQuizQuestions { get; set; }
}
In order for the model binding to work with a IList or any other collection, asp-net expects the form data you post to have sequential indexes. The form data you are sending over POST already has a working example of model binding with collections implemented. Looking at the form data:
The highlighted properties show how to correctly bind to a collection, in that you set the values for the property Correct in the OldQuizAnswers model for each index of IList in OldQuizQAViewModel and pass these all at once in a single request.
Whereas in the same request you only pass the data for OldQuizQuestions of specific index you wish these values to be bound to in the IList collection.
This is why the fist time you post, the model binding works successfully as you are referencing the first index ([0]), whereas on the second POST you reference the second index (1) but not the first, causing the model binding to fail.
See herefor more information on how model binding works.
Have you tried adding a #Html.HiddenFor(model => model.OldQuizQuestions[j]) ?
I read this "It creates a hidden input on the form for the field (from your model) that you pass it.
It is useful for fields in your Model/ViewModel that you need to persist on the page and have passed back when another call is made but shouldn't be seen by the user."
Answer comes from https://stackoverflow.com/a/3866720/8404545
Might be the problem here
I would like to ask is there any way to set an automatic DateTime.Now value for properties ENTRY_DATE and AUDIT_TIME in the Create() HttpPost method? The form is created and it works fine. If the DateTime is inserted manually. But, it won't work if I set an automatic value and would run into a
"One or more validation Error's"..
This is my model (I don't understand how to make a viewmodel) :
public partial class TRRESPONDENT
{
public TRRESPONDENT()
{
this.TRFOLLOWUPRESPONDENTs = new HashSet<TRFOLLOWUPRESPONDENT>();
}
[Required(ErrorMessage = "Respondent ID is required!")]
[Display(Name = "Respondent ID")]
public string RESPONDENT_ID { get; set; }
[Required(ErrorMessage = "Please select a BINUS Center!")]
[Display(Name = "Binus Center")]
public string BC_ID { get; set; }
[Required(ErrorMessage = "Name cannot be empty!")]
[Display(Name = "Name")]
[StringLength(100,ErrorMessage = "Name length cannot be more than 100 characters!")]
public string FULL_NAME { get; set; }
.... // more properties
[Required(ErrorMessage = "Please pick a City Location!")]
[Display(Name = "City")]
public int CITY_ID { get; set; }
// The following 2 properties need to be set
[Display(Name = "Entry Date")]
public DateTime ENTRY_DATE { get; set; }
public DateTime AUDIT_TIME { get; set; }
....
public virtual LTCITY LTCITY { get; set; }
public virtual LTSOURCERESPONDENT LTSOURCERESPONDENT { get; set; }
public virtual MSBINUSCENTER MSBINUSCENTER { get; set; }
public virtual ICollection<TRFOLLOWUPRESPONDENT> TRFOLLOWUPRESPONDENTs { get; set; }
}
This is my view
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
#Html.LabelFor(model => model.RESPONDENT_ID)
#Html.EditorFor(model => model.RESPONDENT_ID)
#Html.ValidationMessageFor(model => model.RESPONDENT_ID)
#Html.LabelFor(model => model.BC_ID, "Binus Center")
#Html.DropDownList("BC_ID", null)
#Html.ValidationMessageFor(model => model.BC_ID)
#Html.LabelFor(model => model.FULL_NAME)
#Html.EditorFor(model => model.FULL_NAME)
#Html.ValidationMessageFor(model => model.FULL_NAME)
.... // more form controls
#Html.LabelFor(model => model.CITY_ID, "City")
#Html.DropDownList("CITY_ID", null)
#Html.ValidationMessageFor(model => model.CITY_ID)
#Html.HiddenFor(model => model.ENTRY_DATE)
#Html.HiddenFor(model => model.AUDIT_TIME)
<input type="submit" value="Create" class="btn btn-default" />
}
This is my controller :
public class RespondentController : Controller
{
private RespondentBINUSEntities db = new RespondentBINUSEntities();
public ActionResult Create()
{
ViewBag.CITY_ID = new SelectList(db.LTCITies, "CITY_ID", "CITY_NAME", 1);
var entry = new Models.TRRESPONDENT
{
ENTRY_DATE = DateTime.Now,
AUDIT_TIME = DateTime.Now,
};
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "RESPONDENT_ID,BC_ID,BINUSIAN_ID,FULL_NAME,EMAIL,PHONE_NUMBER,ADDRESS,CITY_ID,ZIP_CODE,SOURCE_ID,ENTRY_DATE,PACKAGE,AUDIT_USER_NAME,AUDIT_TIME,AUDIT_ACTIVITY")] TRRESPONDENT tRRESPONDENT)
{
if (ModelState.IsValid)
{
db.TRRESPONDENTs.Add(tRRESPONDENT);
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.CITY_ID = new SelectList(db.LTCITies, "CITY_ID", "CITY_NAME", tRRESPONDENT.CITY_ID);
return View(tRRESPONDENT);
}
}
You have not stated the details of the error message, but no doubt this is because you saving a values of 01/01/0001 to a field which which is DATETIME (which only accepts dates between 01/01/1753 to 12/31/9999) and not DATETIME2.
The reason the values of you dates are 01/01/0001 (which is the default for DateTime) is because you do not pass a model to the view so default values are used. The code in your GET needs to be
public ActionResult Create()
{
ViewBag.CITY_ID = new SelectList(db.LTCITies, "CITY_ID", "CITY_NAME", 1);
var entry = new Models.TRRESPONDENT
{
ENTRY_DATE = DateTime.Now,
AUDIT_TIME = DateTime.Now,
};
return View(entry); // return your model
}
However you should not use your data model in the view, and instead create a view model containing only the properties you need. Values such as ENTRY_DATE should only be set immediately before you save the data model to the database. For information on a creating a view model, refer What is ViewModel in MVC?.
The basic steps for creating a view model are
Create a new folder (say) ViewModels and copy you data model to and
and rename it (say)RespondentVM
Delete all the [Display] attributes from you data model (they are
view specific attributes)
Delete all the properties which the user will not be editing in the
view (e.g ENTRY_DATE and AUDIT_TIME) except the property which
is the objects ID which should be renamed to ID so its
automatically bound assuming your using the default routes (note its
not clear if you even have an ID property - I assume its
RESPONDENT_ID, but that should be an auto-incremented int in the
database -i.e. [Key]public int RespondentId { get; set; }). I also
recommend you rename all your properties to follow naming
conventions - EntryDate, not ENTRY_DATE.
Change all value types to be nullable and add the [Required]
attribute to protect against under-posting attacks (e.g. public int
CITY_ID { get; set; } becomes public int? CityID { get; set; }
Add additional properties for SelectList's etc that you are
currently assigning to ViewBag properties, e.g. public
IEnumerable<SelectListItem> CityList { get; set; }
You controller methods will then be
public ActionResult Create()
{
RespondentVM model = new RespondentVM();
ConfigureViewModel(model);
return View(model);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(RespondentVM model) // note a [Bind]` attribute is not required
{
if (!ModelState.IsValid)
{
ConfigureViewModel(model);
return View(model);
}
// Initialize an instance of your data model and set its properties based on the view model
TRRESPONDENT respondent = new TRRESPONDENT()
{
FULL_NAME = model.FullName,
CITY_ID = model.CityID,
....
// Set default values
ENTRY_DATE = DateTime.Now,
....
}
db.TRRESPONDENTs.Add(respondent);
db.SaveChanges();
return RedirectToAction("Index");
}
// Common code for populating SelectLists etc - DRY!
private void ConfigureviewModel(RespondentVM model)
{
// Note - delete the 4th parameter of the SelectList constructor
model.CityID = new SelectList(db.LTCITies, "CITY_ID", "CITY_NAME");
}
And a few extra notes on your view code.
You do not need a hidden input for the ID property if its named ID
and your using the default routing
Since you have [Display(Name = "..")] attributes, then in the view
its just #Html.LabelFor(m => m.PropertyName), not
#Html.LabelFor(m => m.PropertyName, "some text")
To generate your dropdownlists, use #Html.DropDownListFor(m =>
m.CityID, Model.CityList, "Please select", new { ... }); - you
current implementation will not give correct 2-way model binding or
client side validation.
I'm trying to get an integer out of a listitem.
i first collected the items to put in the dropdownlist and then i try to take the integer out of the items
It worked before(got a nice string with interests in database), but more often than not, i get an error for trying to make an integer out of a listitem
I would like to solve this so it works 100% of the time so it doesn't look like an incomplete project when i present this.
<div class="form-group">
#Html.LabelFor(m => m.InteresseLijst1, new { #class = "col-md-2 control-label" })
<div class="col-md-10">
#Html.DropDownListFor(m => m.Interesse1, Model.InteresseLijst1)
</div>
</div>
these are the used properties from my viewmodel
[Display(Name = "Interesse 1")]
public SelectList InteresseLijst1 { get; set; }
[Display(Name = "Interesse 2")]
public SelectList InteresseLijst2 { get; set; }
public int Interesse1 { get; set; }
public int Interesse2 { get; set; }
public string Interesses { get; set; }
this is my Get-action to register where i make my selectlists
public ActionResult Register()
{
RegisterViewModel rvm = new RegisterViewModel();
List<Categorie> categorielijst = CategoryRepository.GetCategories();
rvm.InteresseLijst1 = new SelectList(categorielijst, "CategoryId", "CategoryName");
rvm.InteresseLijst2 = new SelectList(categorielijst, "CategoryId", "CategoryName");
return View(rvm);
}
and this is my post where i use the integers collected from the selectlist.
I convert to json to keep it in my database for further comparison on other parts of the site.
#region verschillend
if(model.Interesse1 != model.Interesse2)
{
int[] interesses = new int[2] { model.Interesse1, model.Interesse2 };
string sInteresses = JsonConvert.SerializeObject(interesses);
model.Interesses = sInteresses;
//other code
return RedirectToAction("Index", "Home");
}
AddErrors(result);
}
#endregion
With a bit of a workaround, i managed to get rid of the error. I changed the way the items are displayed by adding properties to items in a list. Then i collect the values of the properties in my controller with Request.Form["propertyname"] and it worked
I want to get dropdown list with values from table. I'm have model:
namespace MobileService.Models
{
public class Mobile
{
public int Id { get; set; }
public string Model { get; set;}
Public string EMEI { get; set ;}
public int MasterId { get; set; }
public List<Master> MasterList { get; set; }
}
public class Master
{
public int Id { get; set; }
public string Name { get; set; }
}
}
In controller I creat action for this model:
public ActionResult Create()
{
return View();
}
In view:
#model MobileService.Models.Mobile
#using (Html.BeginForm()) {
#Html.EditorFor(model => model.Model)
#Html.EditorFor(model => model.EMEI )
// And here i want to display a dropdown list with all available masters
<button type="submit" class="btn btn-primary">Creat</button>
}
But it always tell me that Model.MasterList is null . But why? In model i told to get list from another model (public List MasterList { get; set; }). Why is it null?
This code is in VB. In the beginning even i looked for a lot of time this is the simple solution i found.
Convert the model into list of selectListItems
Dim lstEmpTypes As New List(Of SelectListItem)
lstTicketWrTypes.Add(New SelectListItem With {.Text = row("Something"), .Value = row("Something")})
'Then load it into a ViewBag
ViewBag.EmpTypes = lstEmpTypes
'And in you View
#Html.DropDownList("selectWrType", New SelectList(ViewBag.EmpTypes , "Value", "Text"), New With {.class = "span3"})
When you query for Mobile you need to Include("MasterList"), or turn lazy loading on on your context (not recommended)
The answer for me was to add this to controller:
public ActionResult Create()
{
ViewBag.MasterId = new SelectList(db.Masters, "Id", "Name");
return View();
}
Then in view to show droplist:
#Html.DropDownList("MasterId", null, htmlAttributes: new { #class = "form-control" })
Thnx ZikO who let me now that list didn't loaded automatical.