Reputation: 3447
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
Upvotes: 0
Views: 490
Reputation: 3447
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;
}
Upvotes: 1