I am sending the list of affiliates from the get method of controller to View via ViewBag(ViewBag.AffiliateData) and expecting to get the same list in controller's HTTP Post Method(myAffiliateList) but receiving value as null. Could you please help me to understand what am I doing wrong here?
NOTE: I am sending the data as hidden because it is not needed to be shown. So I am trying to get 2 values in HTTP-Post method, one which is being selected and other the whole list that is being used to populate the select box dynamically.
Model:
public class ModelOld
{
public string Aname { get; set; }
public string Acode { get; set; }
}
public class ModelNew
{
public string Acode { get; set; }
public IEnumerable<ModelOld> myAffiliateList { get; set; }
}
Controller: UserInvitation.cs
// GET Method
public ActionResult Import()
{
List<ModelOld> affiliateList = new List<ModelOld>();
ModelNew affiliateList1 = new ModelNew();
var affiliateMappingList = Configuration.GetSection("AffiliateMapping").GetChildren();
foreach (var KeyValuePair in affiliateMappingList)
{
affiliateList.Add(new ModelOld()
{
Aname = KeyValuePair.Key,
Acode = KeyValuePair.Value
});
}
affiliateList.Insert(0, new ModelOld { Acode = "", Aname = "--Select Your Affiliate--" });
affiliateList1.myAffiliateList = affiliateList;
ViewBag.AffiliateData = affiliateList1.myAffiliateList;
return View();
}
[HttpPost]
public async Task<ActionResult> ImportAsync(string Acode, IEnumerable<ModelOld> myAffiliateList)
{
//Some Code
}
View: Import.cshtml
@model ModelNew
<!DOCTYPE html>
<html>
<body>
@using (Html.BeginForm("Import", "UserInvitation", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<div class="row">
<div class="form-group">
<div class="col-md-offset-3 col-md-10">
<label class="col-md-offset-3 col-md-2" title="Select Your Affiliate" style="font-size:large;"><b>Affiliate:</b></label>
<select id="affiliate" class="form-control" style="-webkit-appearance:listbox" asp-for="Acode" asp-items="@(new SelectList(ViewBag.AffiliateData,"Acode","Aname"))">
</select>
@Html.HiddenFor(m => m.myAffiliateList, htmlAttributes: new { @Value = ViewBag.AffiliateData })
</div>
</div>
</div>
<br />
<div class="row">
<div class="form-group">
<div class="col-md-offset-3 col-md-10">
<br />
<button type="submit" id="btnSubmitData" title="Click to Invite the Users" class="btn btn-info">
<i class="glyphicon glyphicon-upload"></i> Invite Users
</button>
</div>
</div>
</div>
}
</body>
</html>
Here is a whole working demo:
Model
View
Controller