I have this list in the GET method for a create page:
List<string> users = (from c in _context.NR_Users select c.Name).ToList();
users.Insert(0, "Select");
ViewBag.users = users;
It is displayed like this:
<div class="form-group col-md-4">
<label class="control-label">Prepared By</label>
<select asp-for="Prepared_By" name="Prepared_By" class="form-control" asp-items="#(new SelectList(ViewBag.users))"></select>
<span asp-validation-for="Prepared_By" class="text-danger"></span>
</div>
In the model Prepared_By is a string.
On the create page when I hit submit I get the following error:
ArgumentNullException: Value cannot be null. (Parameter 'items')
pointing to
<select asp-for="Prepared_By" name="Prepared_By" class="form-control" asp-items="#(new SelectList(ViewBag.users))"></select>
There are a couple things I find really interesting about this issue. First of all, in the POST method for the create page if I print the value of Prepared_By it always prints the correct name:
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create([Bind("ID,State_Project_Number,Federal_Project_Number,Name,Route_Number,County,Work_Type,Coordinates,Project_Description,Federal_Aid,Minimal_Project_Verification,CE_Category,Amms,Activities_Agreement,Arch_RE,Hist_RE,Arch_RE_Date,Hist_RE_Date,Through_Lanes,Close_Road,ROW_Acquisition,Access_Control,Fifty_Year_Structure,Agency_Coordination,IPAC_Screening_Zone,Section_404_Permit,Ground_Disturbance,Waterway,Special_Use_Permit,Floodplain,Prepared_By,Approved_By,Adduser,Date_Added")] TypeOne typeOne, bool Assessment)
{
System.Diagnostics.Debug.WriteLine("Prepared by: " + typeOne.Prepared_By);
if (ModelState.IsValid)
{
typeOne.Adduser = User.Identity.Name;
typeOne.Date_Added = DateTime.Today;
System.Diagnostics.Debug.WriteLine("Prepared by again: " + typeOne.Prepared_By);
_context.Add(typeOne);
await _context.SaveChangesAsync();
}
}
However when I try to print it a second time inside the if(ModelState.IsValid) it does not work.
What else is interesting is that I use this exact same list in a different create page and it works just fine:
<div class="form-group col-md-3">
<label class="control-label">DSN PM</label>
<select asp-for="DSN_PM" name="DSN_PM" class="form-control" asp-items="#(new SelectList(ViewBag.users))"></select>
<span asp-validation-for="DSN_PM" class="text-danger"></span>
</div>
public async Task<IActionResult> Create([Bind("ID,State_Project_Number,Federal_Project_Number,Project_Name,County,Memo_Date,From,Authorization,DSN_PM,History,History_PM,Review_Exempt_H,SHPO_Approval_H,Archaeology,Archaeology_PM,Review_Exempt_A,SHPO_Approval_A,ESA_Key,Crayfish,Crayfish_Habitat_Assessment,NLEB_4D,USFWS,USFWS_Type,Mussel_Habitat,Mussel_Stream,Within_Airport,ToPo_Quad_Name,Bat_Habitat,Bars,Coordinates,Natural_Resources_Notes,Adduser,Date_Added,Crayfish_Notes,Mussel_Notes")] Project_Screen project_Screen)
{
if (ModelState.IsValid)
{
project_Screen.Adduser = User.Identity.Name;
project_Screen.Date_Added = DateTime.Today;
_context.Add(project_Screen);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
return View(project_Screen);
}
In the second example I create the list in the exact same way in the GET method and I have never had this issue. What could be the problem?
EDIT: Update from question
Controller:
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create([Bind("ID,State_Project_Number,Federal_Project_Number,Name,Route_Number,County,Work_Type,Coordinates,Project_Description,Federal_Aid,Minimal_Project_Verification,CE_Category,Amms,Activities_Agreement,Arch_RE,Hist_RE,Arch_RE_Date,Hist_RE_Date,Through_Lanes,Close_Road,ROW_Acquisition,Access_Control,Fifty_Year_Structure,Agency_Coordination,IPAC_Screening_Zone,Section_404_Permit,Ground_Disturbance,Waterway,Special_Use_Permit,Floodplain,Prepared_By,Approved_By,Adduser,Date_Added")] TypeOne typeOne, bool Assessment)
{
System.Diagnostics.Debug.WriteLine("Prepared by: " + typeOne.Prepared_By);
if (ModelState.IsValid)
{
typeOne.Adduser = User.Identity.Name;
typeOne.Date_Added = DateTime.Today;
System.Diagnostics.Debug.WriteLine("Prepared by again: " + typeOne.Prepared_By);
_context.Add(typeOne);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
//set the data for ViewBag.users..
List<string> users = (from c in _context.NR_Users select c.Name).ToList();
users.Insert(0, "Select");
ViewBag.users = users;
return View(typeOne);
}
View:
<div class="form-group col-md-4">
<label class="control-label">Prepared By</label>
<select asp-for="Prepared_By" name="Prepared_By" class="form-control" asp-items="#(new SelectList(ViewBag.users,"Id","Name"))"></select>
<span asp-validation-for="Prepared_By" class="text-danger"></span>
</div>
There are a couple of problems here. First of all, the problem persists and nothing has changed. I'm not sure if the code for the view is correct at all, but it is giving me a Object reference not set to an instance of an object. error but I don't really know what it's pointing to. I also don't know why you added ID because I don't use that anywhere and I don't need to.
EDIT 2:
GET method:
// GET: TypeOnes/Create
public IActionResult Create()
{
List<string> users = (from c in _context.NR_Users select c.Name).ToList();
users.Insert(0, "Select");
ViewBag.users = users;
List<string> adminLeads = (from s in _context.NR_Users
where s.User_Type == "Admin" || s.User_Type == "Unit Leader"
select s.Name).ToList();
adminLeads.Insert(0, "Select");
ViewBag.adminLeads = adminLeads.ToList();
List<SelectListItem> options = new()
{
new SelectListItem { Value = "True", Text = "Yes" },
new SelectListItem { Value = "False", Text = "No" }
};
options.Insert(0, new SelectListItem { Value = "Select" });
ViewBag.options = options;
List<SelectListItem> assessments = new()
{
new SelectListItem { Value = "Mussel", Text = "Mussel" },
new SelectListItem { Value = "Crayfish", Text = "Crayfish" },
new SelectListItem { Value = "Both", Text = "Both" },
new SelectListItem { Value = "No", Text = "No" }
};
assessments.Insert(0, new SelectListItem { Value = "Select" });
ViewBag.options = assessments;
List <SelectListItem> reTypes = new()
{
new SelectListItem { Value = "Appendix A short form", Text = "Appendix A short form" },
new SelectListItem { Value = "Review exempt", Text = "Review exempt" },
new SelectListItem { Value = "SHPO", Text = "SHPO" },
new SelectListItem { Value = "Programatic Agreement", Text = "Programatic Agreement" }
};
reTypes.Insert(0, new SelectListItem { Value = "Select", Text = "Select" });
ViewBag.reTypes = reTypes;
List <SelectListItem> counties = new()
{
new SelectListItem { Value = "Barbour", Text = "Barbour County" },
new SelectListItem { Value = "Berkeley", Text = "Berkeley County" },
new SelectListItem { Value = "Boone", Text = "Boone County" },
new SelectListItem { Value = "Braxton", Text = "Braxton County" },
new SelectListItem { Value = "Cabell", Text = "Cabell County" },
new SelectListItem { Value = "Calhoun", Text = "Calhoun County" },
new SelectListItem { Value = "Clay", Text = "Clay County" },
new SelectListItem { Value = "Doddridge", Text = "Doddridge County" },
new SelectListItem { Value = "Fayette", Text = "Fayette County" },
new SelectListItem { Value = "Gilmer", Text = "Gilmer County" },
new SelectListItem { Value = "Grant", Text = "Grant County" },
new SelectListItem { Value = "Greenbrier", Text = "Greenbrier County" },
new SelectListItem { Value = "Hampshire", Text = "Hampshire County" },
new SelectListItem { Value = "Hancock", Text = "Hancock County" },
new SelectListItem { Value = "Hardy", Text = "Hardy County" },
new SelectListItem { Value = "Harrison", Text = "Harrison County" },
new SelectListItem { Value = "Jackson", Text = "Jackson County" },
new SelectListItem { Value = "Jefferson", Text = "Jefferson County" },
new SelectListItem { Value = "Kanawha", Text = "Kanawha County" },
new SelectListItem { Value = "Lewis", Text = "Lewis County" },
new SelectListItem { Value = "Lincoln", Text = "Lincoln County" },
new SelectListItem { Value = "Logan", Text = "Logan County" },
new SelectListItem { Value = "Marion", Text = "Marion County" },
new SelectListItem { Value = "Marshall", Text = "Marshall County" },
new SelectListItem { Value = "Mason", Text = "Mason County" },
new SelectListItem { Value = "McDowell", Text = "McDowell County" },
new SelectListItem { Value = "Mercer", Text = "Mercer County" },
new SelectListItem { Value = "Mineral", Text = "Mineral County" },
new SelectListItem { Value = "Mingo", Text = "Mingo County" },
new SelectListItem { Value = "Monongalia", Text = "Monongalia County" },
new SelectListItem { Value = "Monroe", Text = "Monroe County" },
new SelectListItem { Value = "Morgan", Text = "Morgan County" },
new SelectListItem { Value = "Nicholas", Text = "Nicholas County" },
new SelectListItem { Value = "Ohio", Text = "Ohio County" },
new SelectListItem { Value = "Pendleton", Text = "Pendleton County" },
new SelectListItem { Value = "Pleasants", Text = "Pleasants County" },
new SelectListItem { Value = "Pocahontas", Text = "Pocahontas County" },
new SelectListItem { Value = "Preston", Text = "Preston County" },
new SelectListItem { Value = "Putnam", Text = "Putnam County" },
new SelectListItem { Value = "Raleigh", Text = "Raleigh County" },
new SelectListItem { Value = "Randolph", Text = "Randolph County" },
new SelectListItem { Value = "Ritchie", Text = "Ritchie County" },
new SelectListItem { Value = "Roane", Text = "Roane County" },
new SelectListItem { Value = "Summers", Text = "Summers County" },
new SelectListItem { Value = "Taylor", Text = "Taylor County" },
new SelectListItem { Value = "Tucker", Text = "Tucker County" },
new SelectListItem { Value = "Tyler", Text = "Tyler County" },
new SelectListItem { Value = "Upshur", Text = "Upshur County" },
new SelectListItem { Value = "Wayne", Text = "Wayne County" },
new SelectListItem { Value = "Webster", Text = "Webster County" },
new SelectListItem { Value = "Wetzel", Text = "Wetzel County" },
new SelectListItem { Value = "Wirt", Text = "Wirt County" },
new SelectListItem { Value = "Wood", Text = "Wood County" },
new SelectListItem { Value = "Wyoming", Text = "Wyoming County" }
};
ViewBag.counties = counties;
return View();
}
If I recreate every list in the POST method then I don't get any errors anywhere, it simply sends me back to the create page and does not perform the database insert
POST method:
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create([Bind("ID,State_Project_Number,Federal_Project_Number,Name,Route_Number,County,Work_Type,Coordinates,Project_Description,Federal_Aid,Minimal_Project_Verification,CE_Category,Amms,Activities_Agreement,Arch_RE,Hist_RE,Arch_RE_Date,Hist_RE_Date,Through_Lanes,Close_Road,ROW_Acquisition,Access_Control,Fifty_Year_Structure,Agency_Coordination,IPAC_Screening_Zone,Section_404_Permit,Ground_Disturbance,Waterway,Special_Use_Permit,Floodplain,Prepared_By,Approved_By,Adduser,Date_Added")] TypeOne typeOne, string Assessment, bool Bat)
{
List<string> users = (from c in _context.NR_Users select c.Name).ToList();
users.Insert(0, "Select");
ViewBag.users = users;
List<string> adminLeads = (from s in _context.NR_Users
where s.User_Type == "Admin" || s.User_Type == "Unit Leader"
select s.Name).ToList();
adminLeads.Insert(0, "Select");
ViewBag.adminLeads = adminLeads.ToList();
List<SelectListItem> options = new()
{
new SelectListItem { Value = "True", Text = "Yes" },
new SelectListItem { Value = "False", Text = "No" }
};
options.Insert(0, new SelectListItem { Value = "Select" });
ViewBag.options = options;
List<SelectListItem> assessments = new()
{
new SelectListItem { Value = "Mussel", Text = "Mussel" },
new SelectListItem { Value = "Crayfish", Text = "Crayfish" },
new SelectListItem { Value = "Both", Text = "Both" },
new SelectListItem { Value = "No", Text = "No" }
};
assessments.Insert(0, new SelectListItem { Value = "Select" });
ViewBag.assessments = assessments;
List<SelectListItem> reTypes = new()
{
new SelectListItem { Value = "Appendix A short form", Text = "Appendix A short form" },
new SelectListItem { Value = "Review exempt", Text = "Review exempt" },
new SelectListItem { Value = "SHPO", Text = "SHPO" },
new SelectListItem { Value = "Programatic Agreement", Text = "Programatic Agreement" }
};
reTypes.Insert(0, new SelectListItem { Value = "Select", Text = "Select" });
ViewBag.reTypes = reTypes;
List<SelectListItem> counties = new()
{
new SelectListItem { Value = "Barbour", Text = "Barbour County" },
new SelectListItem { Value = "Berkeley", Text = "Berkeley County" },
new SelectListItem { Value = "Boone", Text = "Boone County" },
new SelectListItem { Value = "Braxton", Text = "Braxton County" },
new SelectListItem { Value = "Cabell", Text = "Cabell County" },
new SelectListItem { Value = "Calhoun", Text = "Calhoun County" },
new SelectListItem { Value = "Clay", Text = "Clay County" },
new SelectListItem { Value = "Doddridge", Text = "Doddridge County" },
new SelectListItem { Value = "Fayette", Text = "Fayette County" },
new SelectListItem { Value = "Gilmer", Text = "Gilmer County" },
new SelectListItem { Value = "Grant", Text = "Grant County" },
new SelectListItem { Value = "Greenbrier", Text = "Greenbrier County" },
new SelectListItem { Value = "Hampshire", Text = "Hampshire County" },
new SelectListItem { Value = "Hancock", Text = "Hancock County" },
new SelectListItem { Value = "Hardy", Text = "Hardy County" },
new SelectListItem { Value = "Harrison", Text = "Harrison County" },
new SelectListItem { Value = "Jackson", Text = "Jackson County" },
new SelectListItem { Value = "Jefferson", Text = "Jefferson County" },
new SelectListItem { Value = "Kanawha", Text = "Kanawha County" },
new SelectListItem { Value = "Lewis", Text = "Lewis County" },
new SelectListItem { Value = "Lincoln", Text = "Lincoln County" },
new SelectListItem { Value = "Logan", Text = "Logan County" },
new SelectListItem { Value = "Marion", Text = "Marion County" },
new SelectListItem { Value = "Marshall", Text = "Marshall County" },
new SelectListItem { Value = "Mason", Text = "Mason County" },
new SelectListItem { Value = "McDowell", Text = "McDowell County" },
new SelectListItem { Value = "Mercer", Text = "Mercer County" },
new SelectListItem { Value = "Mineral", Text = "Mineral County" },
new SelectListItem { Value = "Mingo", Text = "Mingo County" },
new SelectListItem { Value = "Monongalia", Text = "Monongalia County" },
new SelectListItem { Value = "Monroe", Text = "Monroe County" },
new SelectListItem { Value = "Morgan", Text = "Morgan County" },
new SelectListItem { Value = "Nicholas", Text = "Nicholas County" },
new SelectListItem { Value = "Ohio", Text = "Ohio County" },
new SelectListItem { Value = "Pendleton", Text = "Pendleton County" },
new SelectListItem { Value = "Pleasants", Text = "Pleasants County" },
new SelectListItem { Value = "Pocahontas", Text = "Pocahontas County" },
new SelectListItem { Value = "Preston", Text = "Preston County" },
new SelectListItem { Value = "Putnam", Text = "Putnam County" },
new SelectListItem { Value = "Raleigh", Text = "Raleigh County" },
new SelectListItem { Value = "Randolph", Text = "Randolph County" },
new SelectListItem { Value = "Ritchie", Text = "Ritchie County" },
new SelectListItem { Value = "Roane", Text = "Roane County" },
new SelectListItem { Value = "Summers", Text = "Summers County" },
new SelectListItem { Value = "Taylor", Text = "Taylor County" },
new SelectListItem { Value = "Tucker", Text = "Tucker County" },
new SelectListItem { Value = "Tyler", Text = "Tyler County" },
new SelectListItem { Value = "Upshur", Text = "Upshur County" },
new SelectListItem { Value = "Wayne", Text = "Wayne County" },
new SelectListItem { Value = "Webster", Text = "Webster County" },
new SelectListItem { Value = "Wetzel", Text = "Wetzel County" },
new SelectListItem { Value = "Wirt", Text = "Wirt County" },
new SelectListItem { Value = "Wood", Text = "Wood County" },
new SelectListItem { Value = "Wyoming", Text = "Wyoming County" }
};
ViewBag.counties = counties;
System.Diagnostics.Debug.WriteLine("Prepared by: " + typeOne.Prepared_By);
if (ModelState.IsValid)
{
typeOne.Adduser = User.Identity.Name;
typeOne.Date_Added = DateTime.Today;
System.Diagnostics.Debug.WriteLine("Prepared by again: " + typeOne.Prepared_By);
var prep = typeOne.Prepared_By;
typeOne.Prepared_By = prep;
_context.Add(typeOne);
await _context.SaveChangesAsync();
//Send all History and Archaeology Unit Leaders an email
List<string> histAndArchLeads = (from s in _context.NR_Users
where s.User_Type == "Unit Leader" && s.Unit == "History" || s.Unit == "Archaeology"
select s.Email_Address).ToList();
foreach(var email in histAndArchLeads)
{
SendEmail(email);
}
//Send an email to Traci if project needs a Mussel or Crayfish habitat assessement (Natural resources Lead)
if (Assessment != "No" )
{
SendEmail("Cole.k.perry#wv.gov");
}
//Send an email to bat lady if project needs a bat habitat assessement
if (Bat)
{
SendEmail("Cole.k.perry#wv.gov");
}
return RedirectToAction(nameof(Index));
}
return View(typeOne);
}
Can you please check the ASP.NET <form /> element? It should look like this:
<form asp-controller="MyController" asp-action="MyAction" method="post">
<!-- Your controls and etc -->
</form>
First of all, in the POST method for the create page if I print the value of Prepared_By it always prints the correct name
Of course it will print the correct value, because you post the data to backend successfully. But you need to know the dropdown populated data is not stored by Prepared_By. It stores value by using asp-items="#(new SelectList(ViewBag.users))". You do not set the ViewBag.users in your post method, that is why it makes ArgumentNullException error when you post back.
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create([Bind("ID,State_Project_Number,Federal_Project_Number,Name,Route_Number,County,Work_Type,Coordinates,Project_Description,Federal_Aid,Minimal_Project_Verification,CE_Category,Amms,Activities_Agreement,Arch_RE,Hist_RE,Arch_RE_Date,Hist_RE_Date,Through_Lanes,Close_Road,ROW_Acquisition,Access_Control,Fifty_Year_Structure,Agency_Coordination,IPAC_Screening_Zone,Section_404_Permit,Ground_Disturbance,Waterway,Special_Use_Permit,Floodplain,Prepared_By,Approved_By,Adduser,Date_Added")] TypeOne typeOne, bool Assessment)
{
System.Diagnostics.Debug.WriteLine("Prepared by: " + typeOne.Prepared_By);
if (ModelState.IsValid)
{
typeOne.Adduser = User.Identity.Name;
typeOne.Date_Added = DateTime.Today;
System.Diagnostics.Debug.WriteLine("Prepared by again: " + typeOne.Prepared_By);
_context.Add(typeOne);
await _context.SaveChangesAsync();
}
//set the data for ViewBag.users..
List<string> users = (from c in _context.NR_Users select c.Name).ToList();
users.Insert(0, "Select");
ViewBag.users = users;
//return View("ViewName", typeOne);
//if you return Create.cshtml, no need specify the view name
return View(typeOne);
}
As per your second way, be sure to debug your code and to see when it goes. It is impossible if you do not set value for ViewBag.users when you populate the dropdown. Be careful if any difference.
Here is a whole simple working demo:
Model:
public class Test
{
public string Id{ get; set; }
public string Name { get; set; }
}
public class TestModel
{
public string Prepared_By { get; set; }
}
View(Create.cshtml):
Besides, you need use public SelectList(IEnumerable items, string dataValueField, string dataTextField); which will display the correct value and text for dropdown.
model TestModel
<form method="post">
<select asp-for="Prepared_By" name="Prepared_By" class="form-control"
asp-items="#(new SelectList(ViewBag.users,"Id","Name"))"></select>
<input type="submit" value="Post" />
</form>
Controller:
[HttpGet]
public IActionResult Create()
{
var data = new List<User>()
{
new User(){ Id="1",Name= "aa" },
new User(){ Id="2",Name= "bb" },
new User(){ Id="3",Name= "cc" }
};
ViewBag.users = data;
return View();
}
[HttpPost]
public IActionResult Create(TestModel model)
{
ViewBag.users = new List<Test>()
{
new Test(){ MenuCategoryId="1",Content= "aa" },
new Test(){ MenuCategoryId="2",Content= "bb" },
new Test(){ MenuCategoryId="3",Content= "cc" }
};
return View(model);
}
I figured it out. I abstracted the drop down lists to a 3rd method DropDowns() and then called that method in both the GET and POST methods:
public void DropDowns()
{
List<string> users = (from c in _context.NR_Users select c.Name).ToList();
users.Insert(0, "Select");
ViewBag.users = users;
List<string> adminLeads = (from s in _context.NR_Users
where s.User_Type == "Admin" || s.User_Type == "Unit Leader"
select s.Name).ToList();
adminLeads.Insert(0, "Select");
ViewBag.adminLeads = adminLeads.ToList();
List<SelectListItem> options = new()
{
new SelectListItem { Value = "True", Text = "Yes" },
new SelectListItem { Value = "False", Text = "No" }
};
options.Insert(0, new SelectListItem { Value = "Select" });
ViewBag.options = options;
List<SelectListItem> assessments = new()
{
new SelectListItem { Value = "Mussel", Text = "Mussel" },
new SelectListItem { Value = "Crayfish", Text = "Crayfish" },
new SelectListItem { Value = "Both", Text = "Both" },
new SelectListItem { Value = "No", Text = "No" }
};
assessments.Insert(0, new SelectListItem { Value = "Select" });
ViewBag.assessments = assessments;
List<SelectListItem> reTypes = new()
{
new SelectListItem { Value = "Appendix A short form", Text = "Appendix A short form" },
new SelectListItem { Value = "Review exempt", Text = "Review exempt" },
new SelectListItem { Value = "SHPO", Text = "SHPO" },
new SelectListItem { Value = "Programatic Agreement", Text = "Programatic Agreement" }
};
reTypes.Insert(0, new SelectListItem { Value = "Select", Text = "Select" });
ViewBag.reTypes = reTypes;
List<SelectListItem> counties = new()
{
new SelectListItem { Value = "Barbour", Text = "Barbour County" },
new SelectListItem { Value = "Berkeley", Text = "Berkeley County" },
new SelectListItem { Value = "Boone", Text = "Boone County" },
new SelectListItem { Value = "Braxton", Text = "Braxton County" },
new SelectListItem { Value = "Cabell", Text = "Cabell County" },
new SelectListItem { Value = "Calhoun", Text = "Calhoun County" },
new SelectListItem { Value = "Clay", Text = "Clay County" },
new SelectListItem { Value = "Doddridge", Text = "Doddridge County" },
new SelectListItem { Value = "Fayette", Text = "Fayette County" },
new SelectListItem { Value = "Gilmer", Text = "Gilmer County" },
new SelectListItem { Value = "Grant", Text = "Grant County" },
new SelectListItem { Value = "Greenbrier", Text = "Greenbrier County" },
new SelectListItem { Value = "Hampshire", Text = "Hampshire County" },
new SelectListItem { Value = "Hancock", Text = "Hancock County" },
new SelectListItem { Value = "Hardy", Text = "Hardy County" },
new SelectListItem { Value = "Harrison", Text = "Harrison County" },
new SelectListItem { Value = "Jackson", Text = "Jackson County" },
new SelectListItem { Value = "Jefferson", Text = "Jefferson County" },
new SelectListItem { Value = "Kanawha", Text = "Kanawha County" },
new SelectListItem { Value = "Lewis", Text = "Lewis County" },
new SelectListItem { Value = "Lincoln", Text = "Lincoln County" },
new SelectListItem { Value = "Logan", Text = "Logan County" },
new SelectListItem { Value = "Marion", Text = "Marion County" },
new SelectListItem { Value = "Marshall", Text = "Marshall County" },
new SelectListItem { Value = "Mason", Text = "Mason County" },
new SelectListItem { Value = "McDowell", Text = "McDowell County" },
new SelectListItem { Value = "Mercer", Text = "Mercer County" },
new SelectListItem { Value = "Mineral", Text = "Mineral County" },
new SelectListItem { Value = "Mingo", Text = "Mingo County" },
new SelectListItem { Value = "Monongalia", Text = "Monongalia County" },
new SelectListItem { Value = "Monroe", Text = "Monroe County" },
new SelectListItem { Value = "Morgan", Text = "Morgan County" },
new SelectListItem { Value = "Nicholas", Text = "Nicholas County" },
new SelectListItem { Value = "Ohio", Text = "Ohio County" },
new SelectListItem { Value = "Pendleton", Text = "Pendleton County" },
new SelectListItem { Value = "Pleasants", Text = "Pleasants County" },
new SelectListItem { Value = "Pocahontas", Text = "Pocahontas County" },
new SelectListItem { Value = "Preston", Text = "Preston County" },
new SelectListItem { Value = "Putnam", Text = "Putnam County" },
new SelectListItem { Value = "Raleigh", Text = "Raleigh County" },
new SelectListItem { Value = "Randolph", Text = "Randolph County" },
new SelectListItem { Value = "Ritchie", Text = "Ritchie County" },
new SelectListItem { Value = "Roane", Text = "Roane County" },
new SelectListItem { Value = "Summers", Text = "Summers County" },
new SelectListItem { Value = "Taylor", Text = "Taylor County" },
new SelectListItem { Value = "Tucker", Text = "Tucker County" },
new SelectListItem { Value = "Tyler", Text = "Tyler County" },
new SelectListItem { Value = "Upshur", Text = "Upshur County" },
new SelectListItem { Value = "Wayne", Text = "Wayne County" },
new SelectListItem { Value = "Webster", Text = "Webster County" },
new SelectListItem { Value = "Wetzel", Text = "Wetzel County" },
new SelectListItem { Value = "Wirt", Text = "Wirt County" },
new SelectListItem { Value = "Wood", Text = "Wood County" },
new SelectListItem { Value = "Wyoming", Text = "Wyoming County" }
};
ViewBag.counties = counties;
}
GET:
// GET: TypeOnes/Create
public IActionResult Create()
{
DropDowns();
return View();
}
POST:
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create([Bind("ID,State_Project_Number,Federal_Project_Number,Name,Route_Number,County,Work_Type,Coordinates,Project_Description,Federal_Aid,Minimal_Project_Verification,CE_Category,Amms,Activities_Agreement,Arch_RE,Hist_RE,Arch_RE_Date,Hist_RE_Date,Through_Lanes,Close_Road,ROW_Acquisition,Access_Control,Fifty_Year_Structure,Agency_Coordination,IPAC_Screening_Zone,Section_404_Permit,Ground_Disturbance,Waterway,Special_Use_Permit,Floodplain,Prepared_By,Approved_By,Adduser,Date_Added")] TypeOne typeOne, string Assessment, bool Bat)
{
DropDowns();
if (ModelState.IsValid)
{
typeOne.Adduser = User.Identity.Name;
typeOne.Date_Added = DateTime.Today;
_context.Add(typeOne);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
return View(typeOne);
}
And it started working.
I am trying to create power point presentation on the fly (without usage of previuosly created template slide). So far I have results, but experiencing difficulties on adding picture (see code below)
When disable the P.Picture part it is working (means the created pptx file can be opened).
With the P.Picture part PowerPoint proposes repair and removes "found non-readable part" resulting of showing only placeholder of the picture with "Picture can not be shown message". If you expand the pptx in unrepaired state the media folder contains proper picture that can be opened... _rels folder contains file that properly links the existing image file with the image placeholder... I am surely missing sth. but what???
Any help appreciated! Many thanks!
public static void CreatePresentation(string filepath)
{
// Create a presentation at a specified file path. The presentation document type is pptx, by default.
PresentationDocument presentationDoc = PresentationDocument.Create(filepath, PresentationDocumentType.Presentation);
PresentationPart presentationPart = presentationDoc.AddPresentationPart();
presentationPart.Presentation = new Presentation();
SlideMasterIdList sldMasterIdList = new SlideMasterIdList(new SlideMasterId() { Id = (UInt32Value)2147483648U, RelationshipId = "rId1" });
SlideIdList sldIdList = new SlideIdList();
SlideSize sldSize = new SlideSize() { Cx = 2751 * mm / 10, Cy = 1905 * mm / 10, Type = SlideSizeValues.Screen4x3 }; // DIN A4 - Landscape.
NotesSize notesSize = new NotesSize() { Cx = 1905 * mm / 10, Cy = 2751 * mm / 10 }; // DIN A4 - Portrait.
DefaultTextStyle defaultTextStyle = new DefaultTextStyle();
presentationPart.Presentation.Append(sldMasterIdList, sldIdList, sldSize, notesSize, defaultTextStyle);
#region [ SlidePart ]
SlidePart slidePart = presentationPart.AddNewPart<SlidePart>("rId2");
sldIdList.AppendChild<SlideId>(new SlideId() { Id = (UInt32Value)256U, RelationshipId = "rId2" });
slidePart.Slide = new Slide
(
new CommonSlideData
(
new ShapeTree
(
new P.NonVisualGroupShapeProperties
(
new P.NonVisualDrawingProperties() { Id = (UInt32Value)1U, Name = "" },
new P.NonVisualGroupShapeDrawingProperties(),
new ApplicationNonVisualDrawingProperties()
),
new GroupShapeProperties(new DocumentFormat.OpenXml.Drawing.TransformGroup())
)
),
new ColorMapOverride(new MasterColorMapping())
);
ImagePart ip = slidePart.AddImagePart(ImagePartType.Jpeg, "rId2");
MyStream.Position = 0;
ip.FeedData(MyStream);
#endregion
#region [ slideLayoutPart ]
SlideLayoutPart slideLayoutPart = slidePart.AddNewPart<SlideLayoutPart>("rId1");
SlideLayout slideLayout = new SlideLayout
(
new CommonSlideData
(
new ShapeTree
(
new P.NonVisualGroupShapeProperties
(
new P.NonVisualDrawingProperties() { Id = (UInt32Value)1U, Name = "" },
new P.NonVisualGroupShapeDrawingProperties(),
new ApplicationNonVisualDrawingProperties()
),
new GroupShapeProperties
(
new DocumentFormat.OpenXml.Drawing.TransformGroup()
)
)
),
new ColorMapOverride
(
new MasterColorMapping()
)
);
slideLayoutPart.SlideLayout = slideLayout;
#endregion
#region [ slideMasterPart ]
SlideMasterPart slideMasterPart = slideLayoutPart.AddNewPart<SlideMasterPart>("rId1");
SlideMaster slideMaster = new SlideMaster(
new CommonSlideData(new ShapeTree(
new P.NonVisualGroupShapeProperties(
new P.NonVisualDrawingProperties() { Id = (UInt32Value)1U, Name = "" },
new P.NonVisualGroupShapeDrawingProperties(),
new ApplicationNonVisualDrawingProperties()),
new GroupShapeProperties(new DocumentFormat.OpenXml.Drawing.TransformGroup()),
new P.Shape(
new P.NonVisualShapeProperties(
new P.NonVisualDrawingProperties() { Id = (UInt32Value)2U, Name = "Title Placeholder 1" },
new P.NonVisualShapeDrawingProperties(new ShapeLocks() { NoGrouping = true }),
new ApplicationNonVisualDrawingProperties(new PlaceholderShape() { Type = PlaceholderValues.Title })),
new P.ShapeProperties(),
new P.TextBody(
new BodyProperties(),
new ListStyle(),
new Paragraph())))),
new P.ColorMap() { Background1 = D.ColorSchemeIndexValues.Light1, Text1 = D.ColorSchemeIndexValues.Dark1, Background2 = D.ColorSchemeIndexValues.Light2, Text2 = D.ColorSchemeIndexValues.Dark2, Accent1 = D.ColorSchemeIndexValues.Accent1, Accent2 = D.ColorSchemeIndexValues.Accent2, Accent3 = D.ColorSchemeIndexValues.Accent3, Accent4 = D.ColorSchemeIndexValues.Accent4, Accent5 = D.ColorSchemeIndexValues.Accent5, Accent6 = D.ColorSchemeIndexValues.Accent6, Hyperlink = D.ColorSchemeIndexValues.Hyperlink, FollowedHyperlink = D.ColorSchemeIndexValues.FollowedHyperlink },
new SlideLayoutIdList(new SlideLayoutId() { Id = (UInt32Value)2147483649U, RelationshipId = "rId1" }),
new TextStyles(new TitleStyle(), new BodyStyle(), new OtherStyle()));
slideMasterPart.SlideMaster = slideMaster;
slideMasterPart.AddPart(slideLayoutPart, "rId1");
presentationPart.AddPart(slideMasterPart, "rId1");
#endregion
#region [ Theme ]
ThemePart themePart = slideMasterPart.AddNewPart<ThemePart>("rId5");
D.Theme theme = new D.Theme() { Name = "Office Theme" };
D.ThemeElements themeElements = new D.ThemeElements(
new D.ColorScheme(
new D.Dark1Color(new D.SystemColor() { Val = D.SystemColorValues.WindowText, LastColor = "000000" }),
new D.Light1Color(new D.SystemColor() { Val = D.SystemColorValues.Window, LastColor = "FFFFFF" }),
new D.Dark2Color(new D.RgbColorModelHex() { Val = "1F497D" }),
new D.Light2Color(new D.RgbColorModelHex() { Val = "EEECE1" }),
new D.Accent1Color(new D.RgbColorModelHex() { Val = "4F81BD" }),
new D.Accent2Color(new D.RgbColorModelHex() { Val = "C0504D" }),
new D.Accent3Color(new D.RgbColorModelHex() { Val = "9BBB59" }),
new D.Accent4Color(new D.RgbColorModelHex() { Val = "8064A2" }),
new D.Accent5Color(new D.RgbColorModelHex() { Val = "4BACC6" }),
new D.Accent6Color(new D.RgbColorModelHex() { Val = "F79646" }),
new D.Hyperlink(new D.RgbColorModelHex() { Val = "0000FF" }),
new D.FollowedHyperlinkColor(new D.RgbColorModelHex() { Val = "800080" })) { Name = "Office" },
new D.FontScheme(
new D.MajorFont(
new D.LatinFont() { Typeface = "Calibri" },
new D.EastAsianFont() { Typeface = "" },
new D.ComplexScriptFont() { Typeface = "" }),
new D.MinorFont(
new D.LatinFont() { Typeface = "Calibri" },
new D.EastAsianFont() { Typeface = "" },
new D.ComplexScriptFont() { Typeface = "" })) { Name = "Office" },
new D.FormatScheme(
new D.FillStyleList(
new D.SolidFill(new D.SchemeColor() { Val = D.SchemeColorValues.PhColor }),
new D.GradientFill(
new D.GradientStopList(
new D.GradientStop(new D.SchemeColor(new D.Tint() { Val = 50000 },
new D.SaturationModulation() { Val = 300000 }) { Val = D.SchemeColorValues.PhColor }) { Position = 0 },
new D.GradientStop(new D.SchemeColor(new D.Tint() { Val = 37000 },
new D.SaturationModulation() { Val = 300000 }) { Val = D.SchemeColorValues.PhColor }) { Position = 35000 },
new D.GradientStop(new D.SchemeColor(new D.Tint() { Val = 15000 },
new D.SaturationModulation() { Val = 350000 }) { Val = D.SchemeColorValues.PhColor }) { Position = 100000 }
),
new D.LinearGradientFill() { Angle = 16200000, Scaled = true }),
new D.NoFill(),
new D.PatternFill(),
new D.GroupFill()),
new D.LineStyleList(
new D.Outline(
new D.SolidFill(
new D.SchemeColor(
new D.Shade() { Val = 95000 },
new D.SaturationModulation() { Val = 105000 }) { Val = D.SchemeColorValues.PhColor }),
new D.PresetDash() { Val = D.PresetLineDashValues.Solid })
{
Width = 9525,
CapType = D.LineCapValues.Flat,
CompoundLineType = D.CompoundLineValues.Single,
Alignment = D.PenAlignmentValues.Center
},
new D.Outline(
new D.SolidFill(
new D.SchemeColor(
new D.Shade() { Val = 95000 },
new D.SaturationModulation() { Val = 105000 }) { Val = D.SchemeColorValues.PhColor }),
new D.PresetDash() { Val = D.PresetLineDashValues.Solid })
{
Width = 9525,
CapType = D.LineCapValues.Flat,
CompoundLineType = D.CompoundLineValues.Single,
Alignment = D.PenAlignmentValues.Center
},
new D.Outline(
new D.SolidFill(
new D.SchemeColor(
new D.Shade() { Val = 95000 },
new D.SaturationModulation() { Val = 105000 }) { Val = D.SchemeColorValues.PhColor }),
new D.PresetDash() { Val = D.PresetLineDashValues.Solid })
{
Width = 9525,
CapType = D.LineCapValues.Flat,
CompoundLineType = D.CompoundLineValues.Single,
Alignment = D.PenAlignmentValues.Center
}),
new D.EffectStyleList(
new D.EffectStyle(
new D.EffectList(
new D.OuterShadow(
new D.RgbColorModelHex(
new D.Alpha() { Val = 38000 }) { Val = "000000" }) { BlurRadius = 40000L, Distance = 20000L, Direction = 5400000, RotateWithShape = false })),
new D.EffectStyle(
new D.EffectList(
new D.OuterShadow(
new D.RgbColorModelHex(
new D.Alpha() { Val = 38000 }) { Val = "000000" }) { BlurRadius = 40000L, Distance = 20000L, Direction = 5400000, RotateWithShape = false })),
new D.EffectStyle(
new D.EffectList(
new D.OuterShadow(
new D.RgbColorModelHex(
new D.Alpha() { Val = 38000 }) { Val = "000000" }) { BlurRadius = 40000L, Distance = 20000L, Direction = 5400000, RotateWithShape = false }))),
new D.BackgroundFillStyleList(
new D.SolidFill(new D.SchemeColor() { Val = D.SchemeColorValues.PhColor }),
new D.GradientFill(
new D.GradientStopList(
new D.GradientStop(
new D.SchemeColor(new D.Tint() { Val = 50000 },
new D.SaturationModulation() { Val = 300000 }) { Val = D.SchemeColorValues.PhColor }) { Position = 0 },
new D.GradientStop(
new D.SchemeColor(new D.Tint() { Val = 50000 },
new D.SaturationModulation() { Val = 300000 }) { Val = D.SchemeColorValues.PhColor }) { Position = 0 },
new D.GradientStop(
new D.SchemeColor(new D.Tint() { Val = 50000 },
new D.SaturationModulation() { Val = 300000 }) { Val = D.SchemeColorValues.PhColor }) { Position = 0 }),
new D.LinearGradientFill() { Angle = 16200000, Scaled = true }),
new D.GradientFill(
new D.GradientStopList(
new D.GradientStop(
new D.SchemeColor(new D.Tint() { Val = 50000 },
new D.SaturationModulation() { Val = 300000 }) { Val = D.SchemeColorValues.PhColor }) { Position = 0 },
new D.GradientStop(
new D.SchemeColor(new D.Tint() { Val = 50000 },
new D.SaturationModulation() { Val = 300000 }) { Val = D.SchemeColorValues.PhColor }) { Position = 0 }),
new D.LinearGradientFill() { Angle = 16200000, Scaled = true }))) { Name = "Office" });
theme.Append(themeElements);
theme.Append(new D.ObjectDefaults());
theme.Append(new D.ExtraColorSchemeList());
themePart.Theme = theme;
presentationPart.AddPart(themePart, "rId5");
#endregion
P.Picture picture = new P.Picture
(
new P.NonVisualPictureProperties
(
new P.NonVisualDrawingProperties() { Id = (UInt32Value)1026U, Name = "Photo", Description = "" },
new P.NonVisualPictureDrawingProperties
(
new D.PictureLocks() { NoChangeAspect = true }
),
new ApplicationNonVisualDrawingProperties()
),
new D.BlipFill
(
new D.Blip
(
new D.NonVisualPicturePropertiesExtensionList()
) { Embed = "rId2" },
new D.Stretch
(
new D.FillRectangle()
)
),
new P.ShapeProperties
(
new D.Transform2D
(
new D.Offset() { X = 1 * cm, Y = 3 * cm },
new D.Extents() { Cx = 16 * cm, Cy = 14 * cm }
),
new D.PresetGeometry
(
new D.AdjustValueList()
) { Preset = D.ShapeTypeValues.Rectangle }
)
);
slidePart.Slide.CommonSlideData.ShapeTree.AppendChild<P.Picture>(picture);
//Close the presentation handle
presentationDoc.Close();
}
My problem was really very simple - just found it comparing the repaired against genererated version (serialized XML)...
Unrepaired there was in the BlipFill portion the Prefix a: repaired p:...
There are BlipFills both in Presentation and Drawing
So my mistake was in using the D.BlipFill instead of P.BlipFill
Now it works as expected.
Indeed, the author of the post uses the class BlipFill from DocumentFormat.OpenXml.Drawing instead of DocumentFormat.OpenXml.Presentation namespace. The PPTX file is created successfully, but when opening the file in PowerPoint it alerts that the file has to be repaired.
For whose who has a similar problem in other parts of the code, Open XML SDK has a validator that allows to diagnose such issues. This approach is mush simpler than comparing the repaired and unrepaired presentations manually.
The code is below.
OpenXmlValidator validator = new OpenXmlValidator();
var doc = PresentationDocument.Open(pptPath, true);
var errors = validator.Validate(doc);
The errors then contains the issues in the presentation.