ASP.NET MVC: Values are null when they reach the Controller - asp.net-mvc

So I have the following Controller:
[HttpPost]
public ActionResult CreateSupport(CreateSupport model)
{
if (ModelState.IsValid && (model.Description != null))
{
model.CreatedById = UserId;
model.ModifiedById = UserId;
}
return View(model);
}
I have the following view:
#using (Html.BeginForm("CreateSupport", "Support", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
<fieldset>
<legend></legend>
<div class="editor-label">
#Html.LabelFor(model => model.Subject, new Dictionary<string, object>() { { "class", "req" } })
</div>
<div class="editor-field">
#Html.TextBoxFor(m => m.Subject)
#Html.ValidationMessageFor(model => model.Subject)
</div>
<div class="support-form-left">
<div class="editor-label">
#Html.LabelFor(model => model.BrowserInfo, new Dictionary<string, object>() { { "class", "req" } })
</div>
<div class="editor-field">
#Html.TextBoxFor(m => m.BrowserInfo)
#Html.ValidationMessageFor(model => model.BrowserInfo)
</div>
</div>
<div class="support-form-right">
<div class="editor-label">
#Html.LabelFor(model => model.DatabaseVersion, new Dictionary<string, object>() { { "class", "req" } })
</div>
<div class="editor-field">
#Html.TextBoxFor(m => m.DatabaseVersion)
#Html.ValidationMessageFor(model => model.DatabaseVersion)
</div>
</div>
<div class="clearFloat"></div>
<div class="editor-label">
#Html.LabelFor(model => model.Description, new Dictionary<string, object>() { { "class", "req" } })
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Description)
#Html.ValidationMessageFor(model => model.Description)
</div>
<div class="actionButtons">
<button id="btnCancel" class="myButtonCancel">Cancel</button>
<input type="submit" value="Submit" class="myButton" />
</div>
#if (ViewBag.SuccessMessage != null)
{
<div>
<label style="color: red;">#ViewBag.SuccessMessage</label>
</div>
}
</fieldset>
}
Here's the Model:
public class CreateSupport : SupportTicket
{
public CreateSupport()
{
ProductList = new List<Product>();
ProductVersionsList = new List<ProductVersion>();
EnviromentList = new List<InstallationEnvironment>();
content = new Content();
}
[Required]
[UIHint("tinymce_jquery_full"), AllowHtml]
public string Description { get; set; }
[Required]
[DisplayName("Browser version Info.")]
public string BrowserInfo { get; set; }
[Required]
[DisplayName("Database Version")]
public string DatabaseVersion { get; set; }
public Content content { get; set; }
}
The problem is that the values that reach the Controller are NULL even if you enter some value in them.

You should check your browser's developer tools to see if the form is properly posting its values. If it isn't, you should do two things:
A) Disabled javascript to see if there is a script that is interfering with the POST (typically either by disabling or clearing fields)
B) Ensuring your markup is valid using the W3C markup validation service

For input fields use
#Html.EditorFor(x => x.Subject)
For display fields use
#Html.DisplayFor(x => x.Subject)

Related

upload image in server folder and save path in Sqlserver using entity framework mvc4

I am trying to save picture in folder and store path in Sqlserver 2008 using entity framework. I need register the user with picture. My code is saving all the data in database except picture and picture path.
My model is
{
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
public partial class customer
{
[Display(Name="Username")]
public string user_id { get; set; }
[Display(Name = "Password")]
public string password { get; set; }
[Display(Name = "First Name")]
public string first_name { get; set; }
[Display(Name = "Last Name")]
public string last_name { get; set; }
[Display(Name = "Address")]
public string address { get; set; }
[Display(Name = "City")]
public string city { get; set; }
[Display(Name = "State")]
public string state { get; set; }
[Display(Name = "Zip")]
public Nullable<int> zip { get; set; }
[Display(Name = "Country")]
public string country { get; set; }
[Display(Name = "Email Address")]
public string email { get; set; }
[Display(Name = "Phone")]
public string phone { get; set; }
[Display(Name = "Picture")]
public string picture { get; set; }
[Display(Name = "Registration Date")]
public Nullable<System.DateTime> reg_date { get; set; }
[Display(Name = "Status")]
public string status { get; set; }
[Display(Name = "Keep me logged in")]
public bool rememberme { get; set; }
}
}
My Controller is
[HttpPost]
public ActionResult Register(customer customer, HttpPostedFileBase file)
{
if (ModelState.IsValid)
{
if (file != null)
{
file.SaveAs(HttpContext.Server.MapPath("~/image/") + file.FileName);
customer.picture = file.FileName;
}
onlinebookstoreEntities1 db = new onlinebookstoreEntities1();
db.customers.Add(customer);
db.SaveChanges();
return RedirectToAction("Index","Home");
}
return View(customer);
}
and my view is
#using (Html.BeginForm("Register", "Account", FormMethod.Post, new { enctype = "multipart/form-data" })) {
<div class="editor-label">
#Html.LabelFor(model => model.first_name)
</div>
<div class="txtreg">
#Html.EditorFor(model => model.first_name)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.last_name)
</div>
<div class="txtreg">
#Html.EditorFor(model => model.last_name)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.user_id)
</div>
<div class="txtreg">
#Html.EditorFor(model => model.user_id)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.password)
</div>
<div class="txtreg">
#Html.EditorFor(model => model.password)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.address)
</div>
<div class="txtreg">
#Html.EditorFor(model => model.address)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.city)
</div>
<div class="txtreg">
#Html.EditorFor(model => model.city)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.state)
</div>
<div class="txtreg">
#Html.EditorFor(model => model.state)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.zip)
</div>
<div class="txtreg">
#Html.EditorFor(model => model.zip)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.country)
</div>
<div class="txtreg">
#Html.EditorFor(model => model.country)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.email)
</div>
<div class="txtreg">
#Html.EditorFor(model => model.email)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.phone)
</div>
<div class="txtreg">
#Html.EditorFor(model => model.phone)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.picture)
</div>
<div class="btnreg">
<input type="file" id="picture" value="Upload Picture" />
</div>
<div class="txtreg">
#Html.CheckBoxFor(model => model.rememberme) #Html.LabelFor(model => model.rememberme)
</div>
<input type="submit" value="Create Account" name="btnsub" />
}
If you want to save a picture in the database your property have to look like this:
[DisplayName("Billede")]
[MaxLength]
public byte[] PhotoFile { get; set; }
and not:
[Display(Name = "Picture")]
public string picture { get; set; }
You save your picture like this:
#using (Html.BeginForm("Create", "Photo", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
#Html.DisplayNameFor(model => model.PhotoFile)
<input type="file" name="Image" />
And the ActionResult method inside your PhotoController would be
public ActionResult Create(Photo photo, HttpPostedFileBase image)
{
and the actual saving of the photo itself
if (image != null)
{
photo.ImageFileName = image.FileName;
photo.ImageMimeType = image.ContentType;
photo.PhotoFile = new byte[image.ContentLength];
image.InputStream.Read(photo.PhotoFile, 0, image.ContentLength);
}
context.Add<Photo>(photo);
context.SaveChanges();
Hope you can connect the dots.
Mohammad
check your image folder permissions, If not, set it to all read, write, execute permissions. Try to debug the code and check whether the file is null or any exception fires while file.SaveAs called
Saving url into db is quite simple.At the same time you can save the picture in byte format in db.In your customer model you have
Method-1:
Change string type or any other type to byte.
So In this picture if you want to save the picture you convert picture to byte type instead of string in your customer table in db.
//before
[Display(Name = "Picture")]
public string picture { get; set; }
//After changing in db you add the table in entity framework .edmx and now it becomes
[Display(Name = "Picture")]
public byte[] picture { get; set; }
Here follows your code to save picture in byte format in db.
In your controller
public ActionResult Register(customer model)
{
string ImageName = Path.GetFileName(file.FileName);
string physicalPath = Server.MapPath("~/images/" + ImageName);
file.SaveAs(physicalPath);
customer newRecord = new customer ();
newRecord.username= customer.username;
\\Assign for remaining feilds in table in this way.
using (MemoryStream ms = new MemoryStream())
{
file.InputStream.CopyTo(ms);
byte[] picArray = ms.GetBuffer();
newRecord.picture= picArray ;
}
onlinebookstoreEntities1 db = new onlinebookstoreEntities1();
db.customers.Add(newRecord);
db.SaveChanges();
}
In your Register View
<div>
#using (Html.BeginForm("ConfigAssetData", "Home", new { #tabno = "3" }, FormMethod.Post, new { enctype = "multipart/form-data", #class = "form-horizontal" }))
{
<div class="editor-label">
#Html.LabelFor(model => model.first_name)
</div>
<div class="txtreg">
#Html.EditorFor(model => model.first_name)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.last_name)
</div>
<div class="txtreg">
#Html.EditorFor(model => model.last_name)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.user_id)
</div>
<div class="txtreg">
#Html.EditorFor(model => model.user_id)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.password)
</div>
<div class="txtreg">
#Html.EditorFor(model => model.password)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.address)
</div>
<div class="txtreg">
#Html.EditorFor(model => model.address)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.city)
</div>
<div class="txtreg">
#Html.EditorFor(model => model.city)
</div>
#*UploadFile*#
**<input type="file" class="file-input" name="file"/>**
#*Similar code here...*#
}
</div>
Method-2:
Especially in your case as you need to save picture path what you all need to do is:-
In your Controller
public ActionResult Register(customer model)
{
string ImageName = Path.GetFileName(file.FileName);
string physicalPath = Server.MapPath("~/images/" + ImageName);
file.SaveAs(physicalPath);
customer newRecord = new customer ();
newRecord.username= customer.username;
//.......saving picture url......
newRecord.picture = physicalPath;
//Assign for remaining feilds in table in this way.
onlinebookstoreEntities1 db = new onlinebookstoreEntities1();
db.customers.Add(newRecord);
db.SaveChanges();
}
If you right click on your images folder and click "Open folder in windows explorer" you can see your pic uploaded.

How do I pass a ViewModel to an Edit Action in ASP.NET MVC 5

I'm learning about using ViewModels to pass information from the view to the controller and vice versa. I have my create action, view, and viewmodel working perfectly but I'm having trouble with the edit one. I get the error:
The model item passed into the dictionary is of type 'CatVM.Models.Cat', but this dictionary requires a model item of type 'CatVM.Models.EditCatViewModel'.
Here is my code:
Controller Method
// GET: /Cats/Edit/5
public ActionResult Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Cat cat = unitOfWork.CatRepository.GetByID(id);
if (cat == null)
{
return HttpNotFound();
}
return View(cat);
}
View
#model CatVM.Models.EditCatViewModel
#{
ViewBag.Title = "Edit";
}
<h2>Edit</h2>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Cat</h4>
<hr />
#Html.ValidationSummary(true)
#Html.HiddenFor(model => model.ID)
<div class="form-group">
#Html.LabelFor(model => model.Name, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Name)
#Html.ValidationMessageFor(model => model.Name)
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Color, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Color)
#Html.ValidationMessageFor(model => model.Color)
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.FurLength, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.FurLength)
#Html.ValidationMessageFor(model => model.FurLength)
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Size, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Size)
#Html.ValidationMessageFor(model => model.Size)
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Save" class="btn btn-default" />
</div>
</div>
</div>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
EditCatViewModel
public class EditCatViewModel
{
public int ID { get; set; }
[Required]
[StringLength(50)]
public string Name { get; set; }
[Required]
[StringLength(50)]
public string Color { get; set; }
[Required]
[StringLength(50)]
[Display(Name = "Fur Type")]
public string FurLength { get; set; }
[StringLength(50)]
public string Size { get; set; }
}
}
That's because the item you receive from CatRepository.GetByID(id); is of type Cat, not EditCatViewModel.
You can bypass this by constructing a new viewmodel from this object:
Cat cat = unitOfWork.CatRepository.GetByID(id);
var viewModel = new EditCatViewModel {
Name = cat.Name,
Color = cat.Color,
FurLength = cat.FurLength,
Size = cat.Size
};
return View(viewModel);
Alternatively you could construct implicit or explicit casting methods or use a mapping tool like AutoMapper.
Your return view should be of type CatVM.Models.EditCatViewModel now your returning a Cat
return View(cat);
transform your model in a view model and pass this object back to the view

ASP.NET MVC 4 Create method has null object

I have problem with creating object but I don't know why. I have null object in parameter in Post Create method and in ModelState I get this error:
{System.InvalidOperationException: The parameter conversion from type
'System.String' to type 'BlanskoMenu.Models.ActionOffer' failed
because no type converter can convert between these types. at
System.Web.Mvc.ValueProviderResult.ConvertSimpleType(CultureInfo
culture, Object value, Type destinationType) at
System.Web.Mvc.ValueProviderResult.UnwrapPossibleArrayType(CultureInfo
culture, Object value, Type destinationType) at
System.Web.Mvc.ValueProviderResult.ConvertTo(Type type, CultureInfo
culture) at
System.Web.Mvc.DefaultModelBinder.ConvertProviderResult(ModelStateDictionary
modelState, String modelStateKey, ValueProviderResult
valueProviderResult, Type destinationType)}
These are my methods in controller:
//
// GET: /Action/
public ActionResult Index()
{
var offers = _repository.GetAllActionOffers();
return View(offers);
}
//
// GET: /Action/Create
public ActionResult Create()
{
return View();
}
//
// POST: /Action/Create
[HttpPost]
public ActionResult Create(ActionOffer action)
{
try
{
if (ModelState.IsValid)
{
_repository.CreateActionOffer(action);
return RedirectToAction("Index");
}
return View(action);
}
catch
{
return View(action);
}
}
This is my ActionOffer model:
public class ActionOffer
{
[Key]
public int Id { get; set; }
public string Text { get; set; }
public string Title { get; set; }
public string ImagePath { get; set; }
[DataType(DataType.Date)]
public DateTime StartDate { get; set; }
[DataType(DataType.Date)]
public DateTime EndDate { get; set; }
}
And this is my Create view:
#model BlanskoMenu.Models.ActionOffer
#{
ViewBag.Title = "Vytvořit akční nabídku";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Vytvořit akční nabídku</h2>
#using (Html.BeginForm()) {
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
<fieldset>
<legend>Akční nabídka</legend>
#Html.HiddenFor(model => model.Id)
<div class="editor-label">
#Html.LabelFor(model => model.Title)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Title)
#Html.ValidationMessageFor(model => model.Title)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Text)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Text)
#Html.ValidationMessageFor(model => model.Text)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.ImagePath)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.ImagePath)
#Html.ValidationMessageFor(model => model.ImagePath)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.StartDate)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.StartDate)
#Html.ValidationMessageFor(model => model.StartDate)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.EndDate)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.EndDate)
#Html.ValidationMessageFor(model => model.EndDate)
</div>
<p>
<input type="submit" value="Save" />
</p>
</fieldset>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
Thanks for help
Try changing
public ActionResult Create(ActionOffer action)
to
public ActionResult Create(ActionOffer actionOffer)

EF database-first generated form won't validate

I've just created a new controller, along with its CRUD forms, etc, with a database-first EF model/entity.
Its throwing a number of validation errors on save, but since the form has validators, I don't see why this would be so.
For reasons that are beyond me, I'm not getting any validation to happen at all. It just goes right in to the saveChanges() call, which promptly fails.
Here's the edit form:
#model StatementsApplication.DAL.StatementTask
#{
ViewBag.Title = "Edit";
}
<h2>Edit</h2>
<script src="#Url.Content("~/Scripts/jquery.validate.min.js")"></script>
<script src="#Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")"></script>
#using (Html.BeginForm()) {
#Html.ValidationSummary(true)
<fieldset>
<legend>StatementTask</legend>
<div class="editor-label">
#Html.LabelFor(model => model.sInitials)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.sInitials)
#Html.ValidationMessageFor(model => model.sInitials)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.dtCompleted)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.dtCompleted)
#Html.ValidationMessageFor(model => model.dtCompleted)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.sGroupLabel)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.sGroupLabel)
#Html.ValidationMessageFor(model => model.sGroupLabel)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.nGroupSequence)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.nGroupSequence)
#Html.ValidationMessageFor(model => model.nGroupSequence)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.sTaskType)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.sTaskType)
#Html.ValidationMessageFor(model => model.sTaskType)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.sTaskLabel)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.sTaskLabel)
#Html.ValidationMessageFor(model => model.sTaskLabel)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.nTaskSequence)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.nTaskSequence)
#Html.ValidationMessageFor(model => model.nTaskSequence)
</div>
#Html.HiddenFor(model => model.ID)
<p>
<input type="submit" value="Save" />
</p>
</fieldset>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
and here's the generated model:
namespace StatementsApplication.DAL
{
using System;
using System.Collections.Generic;
public partial class StatementTask
{
public int StmtBatchID { get; set; }
public string sInitials { get; set; }
public Nullable<System.DateTime> dtCompleted { get; set; }
public string sGroupLabel { get; set; }
public double nGroupSequence { get; set; }
public string sTaskType { get; set; }
public string sTaskLabel { get; set; }
public double nTaskSequence { get; set; }
public int ID { get; set; }
public virtual StatementBatch tblStmtBatch { get; set; }
}
}
and here's the controller bits...
//
// GET: /StatementTask/Edit/5
public ActionResult Edit(int id = 0)
{
StatementTask statementtask = db.StatementTasks.Find(id);
if (statementtask == null)
{
return HttpNotFound();
}
ViewBag.StmtBatchID = new SelectList(db.StatementBatches, "ID", "sStatus", statementtask.StmtBatchID);
return View(statementtask);
}
//
// POST: /StatementTask/Edit/5
[HttpPost]
public ActionResult Edit(StatementTask statementtask)
{
if (ModelState.IsValid)
{
try
{
db.Entry(statementtask).State = EntityState.Modified;
db.SaveChanges();
}
catch (Exception ex) {
throw ex;
}
return RedirectToAction("Index");
}
ViewBag.StmtBatchID = new SelectList(db.StatementBatches, "ID", "sStatus", statementtask.StmtBatchID);
return View(statementtask);
}
Its a matter of some confusion for me as to why sInitials is throwing 'required' validation errors, as well as why sGroupLabel is throwing length validation errors.
Thanks
a) your model has no data validation annotations. As such, MVC doesn't do any validation, because you're not telling it what to validate.
b) You don't mention what you are submitting. Are you just submitting an empty form?
it appears that Data Annotations will resolve this issue
[Required(AllowEmptyStrings = true)]
[DisplayFormat(ConvertEmptyStringToNull = false)]
public object Note { get; set; }
via http://fendy-huang.blogspot.com/2011/04/how-to-pass-empty-string-in-entity.html

MVC 3 dropdown list not getting any values

I have a dropdownlist in an MVC 3 create page, however I am not getting any values when I POST the page. My code is as follows :-
View :-
#using (Html.BeginForm("Create", "League", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
#Html.ValidationSummary(true)
League
<div class="editor-label">
#Html.LabelFor(model => model.League.fk_CountryID, "Country")
</div>
<div class="editor-field">
#Html.DropDownList("fk_CountryID", "--Select One--") *
#Html.ValidationMessageFor(model => model.League.fk_CountryID)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.League.LeagueName)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.League.LeagueName)
#Html.ValidationMessageFor(model => model.League.LeagueName)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.League.Image)
</div>
<div class="editor-field">
Upload File: <input type="file" name="Image" />
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
Controller :-
[HttpPost]
public ActionResult Create([Bind(Exclude = "Image")]Country country, HttpPostedFileBase Image, League league)
{
if (ModelState.IsValid)
{
model.League = league;
try
{
foreach (string file in Request.Files)
{
HttpPostedFileBase fileUploaded = Request.Files[file];
if (fileUploaded.ContentLength > 0)
{
byte[] imageSize = new byte[fileUploaded.ContentLength];
fileUploaded.InputStream.Read(imageSize, 0, (int)fileUploaded.ContentLength);
model.League.Image = imageSize;
}
}
db.Leagues.AddObject(model.League);
db.SaveChanges();
return RedirectToAction("Index");
}
catch (Exception e)
{
ModelState.AddModelError("uploadError", e);
}
}
What am I doing wrong? Cannot get the dropdownlist value in the controller.
Thanks for your help and time
Ok fixed it by adding a SelectList in my ViewModel as follows :-
//Countries dropdown List
public SelectList CountryList { get; set; }
public string SelectedCountry { get; set; }
public LeagueData PopulateCountriesDDL(string selected, Country country)
{
var typeList = new SelectList(db.Countries.ToList(), "CountryID", "CountryName", selected);
LeagueData model = new LeagueData { CountryList = typeList, Country = country, SelectedCountry = selected };
return model;
}

Resources