Model is null in view on foreach - asp.net

I have added a list to my view model but when I access it in a foreach loop in the view it throws:
NullReferenceException: Object reference not set to an instance of an object.
AspNetCore.Views_MyActivationCampaign_Campaign.ExecuteAsync() in Campaign.cshtml
+ foreach(var dp in Model.DpRestrictedList)
This is the list I have added:
public List<DpRestricted> DpRestrictedList { get; set; } = new List<DpRestricted>()
{
new DpRestricted(){DpId = 1, Name = "Post Restricted" },
new DpRestricted(){DpId = 2, Name = "Unrestricted" },
new DpRestricted(){DpId = 3, Name = "Customer Restricted" }
};
}
public class DpRestricted
{
public int DpId { get; set; }
public string Name { get; set; }
}
and I am trying to loop over it like this:
<div class="row">
<fieldset>
<legend>Delivery Methods</legend>
<div id="radio">
#*<input type="radio" id="new-method">
<label for="new-method">New Method</label>
<input type="radio" id="dm-101" checked="checked">
<label for="dm-101">DM_101</label>
<input type="radio" id="delivery-method-2">
<label for="delivery-method-2">Delivery Method 2</label>*#
#{
foreach(var dp in Model.DpRestrictedList)
{
#Html.RadioButtonFor(model => model.DeliveryPointRestrictionId, dp);
}
}
</div>
</fieldset>
</div>
Using statement and example:
#model WorkstreamX.Web.Core.ViewModels.ActivationCampaignViewModel
...
<div class="col-md-4">
<label for="headline">Campaign</label>
#Html.EditorFor(model => model.CampaignName, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.CampaignName)
</div>
The above is the using statement in the view and an example of how it is already being used elsewhere in it. When I check it is not just the list that is null but the Model in the loop statement is also null. Is it a case of me needing to new up the view model in the controller at this point? That is what I am about to try I just wanted to state this question and maybe find out why this is happening. Any advice here greatly appreciated.
[edit] How I fixed this issue:
I added an argument to my view:
before return View();
after return View(new ActivationCampaignViewModel());
I still don't quite understand the why of this as I appeared to have a model before. I am assuming that because I didn't call the constructor the list wasn't constructed and made it all fall over.

Your code should be like the below one.
Public ActionResult GetEmployee()
{
var employee = GetEmployee();
return View(employee);
}
#model IEnumerable<Appname.ViewModel.Employee>
#{
foreach(var data in Model) {}
}

How I fixed this issue:
I added an argument to my view:
before return View();
after return View(new ActivationCampaignViewModel());
I still don't quite understand the why of this as I appeared to have a model before. I am assuming that because I didn't call the constructor the list wasn't constructed and made it all fall over.

Related

dropdownlistfor yields error ,{"Object reference not set to an instance of an object."} , when I click submit button

I am trying to create sub category for categories. User first select the categories from dropdownlist and then type the subcategory name and clicks submit. Even though dropdownlist elements are properly fill the dropdown list. When I click submit button It creates error. How can I solve this?
My View:
#model CETAPPSUGG.Models.CategorySubCategoryModel
#{
ViewBag.Title = "Create";
}
<h2>Create</h2>
#using (Html.BeginForm())
{
#Html.HiddenFor(model => model.selectedId, new { id = "3" });
// #Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>SubCatagories</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.SubCategory.SubCategoryName, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.SubCategory.SubCategoryName, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.SubCategory.SubCategoryName, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
Upper cat: <div class="col-md-10">
#Html.DropDownListFor(Model => Model.Categories, Model.categoryList)
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
My Controller:
public ActionResult Create()
{
var categories = db.Categories.ToList();
CategorySubCategoryModel deneme = new CategorySubCategoryModel();
var list = new List<SelectListItem>();
deneme.Categories = categories;
foreach (Categories c in categories)
{
list.Add(new SelectListItem() { Text = c.CategoryName, Value = c.Id.ToString() });
}
deneme.categoryList = list;
return View(deneme);
}
// POST: SubCatagories/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
// [ValidateAntiForgeryToken]
public ActionResult Create( CategorySubCategoryModel model)
{
string strDDLValue = model.selectedId;
SubCatagories newSubCategory = new SubCatagories();
Categories cat = new Categories();
cat = db.Categories.Find(Convert.ToInt32(strDDLValue));
// cat = db.Categories.Find(Convert.ToInt32(strDDLValue));
newSubCategory.SubCategoryName = model.SubCategory.SubCategoryName;
newSubCategory.UpperCategory = Convert.ToInt32(strDDLValue);
newSubCategory.Categories = cat;
db.SubCatagories.Add(newSubCategory);
db.SaveChanges();
return View();
}
My Model
namespace CETAPPSUGG.Models
{
public class CategorySubCategoryModel
{
SubCatagories SubCatagories { get; set; }
public IEnumerable<Categories> Categories { get; set; }
public IEnumerable<SubCatagories> SubCategories { get; set; }
public IEnumerable<SelectListItem> categoryList { get; set; }
public SubCatagories SubCategory { get; set; }
public string selectedId;
}
}
It creates error in view
You have a bunch of problems here.
Your primary problem is that you are not passing a model back to the View on post, thus the model is null. So, when you attempt to dereference items from the model in the View, a null reference is generated.
First, you are using selectedId but do not set this anywhere. It doesn't get set by magic. What you probably want is #Html.DropDownListFor(model => model.selectedId, Model.categoryList) (note the lowercase m in model in the first parameter, and uppercase M in the second)
Second, don't use a Model in your lambda in the DropDownListFor, use the lowercase model, because uppercase Model is reserved for the actual Model instance. If you want to reference the Model instance, then do something like DropDownListFor(_ => Model.Foo, Model.Foos). Note that I replaced the Model before the lambda with an underscore or some other value that is not Model. Frankly i'm surprised this even works, but there's probably a scoping rule here that overrides the outer Model. Avoid this because it can cause you confusion down the road.
Third, you are passing an IEnumerable to the DropDownListFor as the selected item variable, this won't work on a number of levels. This needs to be a single string value in most cases (sometimes a numerical one, but always a single more basic type that can have ToString() called on it and get a sensible string since DropDownListFor can't display complex objects).
Fourth, You also need to re-populate your DropDownListFor in the Post action, because the contents of a dropdownlist are not posted back, and thus will be null in the model. This, along with the SubCategory derefences in your view are ultimately what is generating the Null Reference exception.
You also need to pass the model back to your view in the Post, but as stated above, it needs to be re-initialized with the Categories as well as SubCategories.
There are probably more problems here, but fix these and you should be on your way.

MVC update ListboxFor with selected values from DropDownListFor

I'm currently working on a website in MVC, I have created a partial view with a DropDownListFor everytime a value is selected in the DropDownListFor it goes to the HttpPost and adds the value to a List. I also have a ListBoxFor that is bound to this list.
What I would like to achieve:
Everytime a new value is added to the List with the DropDownListFor it should update the ListBoxFor automatically so the selected value gets added to this Listbox. I wonder what the best way would be to achieve this.
Code:
Submit.cshtml:
<div class="create-ingredient">
#Html.Partial("_CreateIngredient")
</div>
<br/>
<div class="add-ingredient">
#Html.Partial("_AddIngredient")
</div>
<br/>
<div class="ingredient-listbox">
#Html.LabelFor(model => model.Ingredients,"Current Ingredients")
#Html.ListBoxFor(model => model.Ingredients, new MultiSelectList(Model.SelectedIngredients), new { style = "width:50%;" })
</div>
_AddIngredient.cshtml (Partial View):
#model Recepten.Models.IngredientSelectModel
#using (Ajax.BeginForm("AddIngredient", "Recipe", new AjaxOptions() { UpdateTargetId = "add-ingredient", HttpMethod = "Post" }))
{
#Html.LabelFor(model => model.Ingredients, "Add Ingredient")
#Html.DropDownListFor(model => model.SelectedIngredient, Model.Ingredients, "Select Ingredient", new { #onchange = "$(this).parents('form').submit();" })
}
AddIngredient:
[HttpPost]
public ActionResult AddIngredient(IngredientSelectModel ing)
{
ing.SelectedIngredients.Add(ing.SelectedIngredient);
return PartialView(ing);
}
IngredientSelectModel:
public RecipeModel Recipe { get; set; }
public IEnumerable<SelectListItem> Ingredients { get; set; }
public int SelectedIngredient { get; set; }
public string addIngredient { get; set; }
public List<int> SelectedIngredients { get; set; }
public IngredientSelectModel()
{
SelectedIngredients = new List<int>();
}
Thank you for your time!
As I think you've figured, the reason the current approach isn't working is that the IngredientSelectModel created for and updated by the AddIngredient action is separate from the one used to populate the ListBox.
If Ajax and unobtrusive JQuery are set up correctly (the browser URL shouldn't change when you select an ingredient), #pinhead's answer will send the selected value to the action, but SelectedIngredients won't accumulate the values you select because its value isn't included in the ajax data. For that to work you need to change the multi-select to be bound to SelectedIngredients:
#Html.ListBoxFor(
model => model.SelectedIngredients,
new MultiSelectList(Model.SelectedIngredients),
new { style = "width:50%;" })
...and move it inside the form declaration so its value is posted to the action along with the new ingredient to add.
That said, I wouldn't say you're doing enough work to justify a round-trip to the server, so after making the above change you could just add the ingredient entirely on the client side like this:
#Html.DropDownListFor(
model => model.SelectedIngredient,
Model.Ingredients,
"Select Ingredient",
new { #onchange = "$('#SelectedIngredients').append('<option>' + $(this).val() + '</option>')" })
I believe one solution is to move your ListBoxFor helper into your partial view so that it is updated and recreated once your action returns the partial view.
Submit.cshtml:
<div class="create-ingredient">
#Html.Partial("_CreateIngredient")
</div>
<br/>
<div class="add-ingredient">
#Html.Partial("_AddIngredient")
</div>
_AddIngredient.cshtml (Partial View):
#model Recepten.Models.IngredientSelectModel
#using (Ajax.BeginForm("AddIngredient", "Recipe", new AjaxOptions() { UpdateTargetId = "add-ingredient", HttpMethod = "Post" }))
{
#Html.LabelFor(model => model.Ingredients, "Add Ingredient")
#Html.DropDownListFor(model => model.SelectedIngredient, Model.Ingredients, "Select Ingredient", new { #onchange = "$(this).parents('form').submit();" })
}
#Html.LabelFor(model => model.Ingredients,"Current Ingredients")
#Html.ListBoxFor(model => model.Ingredients, new MultiSelectList(Model.SelectedIngredients), new { style = "width:50%;" })

MVC 5 - two separate models on a page, how do I attach one to a form so I can submit it?

TL;DR: How do I handle form data that is being submitted with nonstandard names for the data?
The stats:
MVC 5
ASP.NET 4.5.2
I am bringing in two different models:
public async Task<ActionResult> Index() {
var prospectingId = new Guid(User.GetClaimValue("CWD-Prospect"));
var cycleId = new Guid(User.GetClaimValue("CWD-Cycle"));
var viewModel = new OnboardingViewModel();
viewModel.Prospecting = await db.Prospecting.FindAsync(prospectingId);
viewModel.Cycle = await db.Cycle.FindAsync(cycleId);
return View(viewModel);
}
One called Prospecting, the other called Cycle. The Prospecting one is working just fine, as nothing else on the page needs it except one small item.
The Cycle has a mess of separate forms on the page, each needing to be separately submittable, and editing just one small part of the Cycle table. My problem is, I don't know how to submit the correct data to the backend. I am also not entirely sure how to "catch" that data.
The bright spot is that apparently the front end is properly reflective of what is in the db. As in, if I manually change the db field to a true value, the checkbox ends up being selected on refresh.
My current form is such:
#using(Html.BeginForm("UpdatePDFResourceRequest", "Onboarding", FormMethod.Post, new { enctype = "multipart/form-data" })) {
#Html.AntiForgeryToken()
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<fieldset>
#Html.LabelFor(Model => Model.Cycle.PDFResourceLibrary, htmlAttributes: new { #class = "control-label" })
#Html.CheckBoxFor(Model => Model.Cycle.PDFResourceLibrary, new { #class = "form-control" })
#Html.ValidationMessageFor(Model => Model.Cycle.PdfResourceLibrary, "", new { #class = "text-danger" })
<label class="control-label"> </label><button type="submit" value="Save" title="Save" class="btn btn-primary glyphicon glyphicon-floppy-disk"></button>
</fieldset>
}
But the resulting HTML is such:
<input id="Cycle_PDFResourceLibrary" class="form-control" type="checkbox" value="true" name="Cycle.PDFResourceLibrary" data-val-required="'P D F Resource Library' must not be empty." data-val="true">
As you can see, the name= is Cycle.PDFResourceLibrary and I don't know how to catch this on the backend.
My model for that specific form is:
public class PDFResourceRequestViewModel {
[DisplayName("PDF Resource Library Request")]
public bool PDFResourceLibrary { get; set; }
[DisplayName("Date Requested")]
[DataType(DataType.Date)]
public DateTime PDFResourceLibraryDate { get; set; }
[DisplayName("Notes")]
public string PDFResourceLibraryNotes { get; set; }
}
(not the overall model for that table, though)
And the method used to handle the form submission is:
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> UpdatePDFResourceRequest(PDFResourceRequestViewModel model) {
var id = new Guid(User.GetClaimValue("CWD-Cycle"));
Cycle cycle = await db.Cycle.FindAsync(id);
if(cycle == null) {
return HttpNotFound();
}
try {
cycle.CycleId = id;
cycle.PDFResourceLibrary = model.PDFResourceLibrary;
cycle.PDFResourceLibraryDate = DateTime.Now;
cycle.PDFResourceLibraryNotes = model.PDFResourceLibraryNotes;
db.Cycle.Add(cycle);
await db.SaveChangesAsync();
return RedirectToAction("Index");
} catch { }
return View(model);
}
Now, I know that the method is wrong, for one I am editing just three values out of dozens in that table, so I need to be using something like this method. Problem is, the form is getting submitted with the name= of Cycle.PDFResourceLibrary and it is not being matched up on the back end.
Help?
You can use the [Bind(Prefix="Cycle")] attribute to 'strip' the prefix so that name="Cycle.PDFResourceLibrary" effectively becomes name="PDFResourceLibrary" and will bind to your PDFResourceRequestViewModel
public async Task<ActionResult> UpdatePDFResourceRequest([Bind(Prefix="Cycle")]PDFResourceRequestViewModel model)

MVC 4 Html.Editor ignores EditorTemplate

I'm trying to implement some custom EditorTemplates but they're only being rendered by my Create view, and not the Edit one.
Model
public class Page {
public int PageID { get; set; }
[DataType(DataType.Html)]
[AllowHtml]
// I tried including [UIHint("Html")] but this made no difference
public string Content { get; set; }
...
}
/Views/Shared/EditorTemplates/Html.cshtml
#model string
#Html.TextArea("", Model, new { #class = "html"})
/Views/Shared/EditorTemplates/Object.cshtml
#if (ViewData.TemplateInfo.TemplateDepth > 1)
{
#ViewData.ModelMetadata.SimpleDisplayText
} else {
#Html.ValidationSummary(false)
foreach (var prop in ViewData.ModelMetadata.Properties.Where(pm => pm.ShowForEdit
&& !ViewData.TemplateInfo.Visited(pm)))
{
if (prop.HideSurroundingHtml) {
#Html.Editor(prop.PropertyName)
#prop.DataTypeName
} else {
<div class="form-field">
#if (!String.IsNullOrEmpty(Html.Label(prop.PropertyName).ToHtmlString())) {
#Html.Label(prop.PropertyName)
}
#Html.Editor(prop.PropertyName)
</div>
}
}
}
/Views/Page/Create.cshtml ( This correctly renders Html.cshtml )
#model MvcDisplayTemplates.Models.Page
#using (Html.BeginForm()) {
#Html.EditorForModel(Model)
<p><input type="submit" value="Create" /></p>
}
/Views/Page/Edit.cshtml ( This simply renders the default single line text editor )
#model MvcDisplayTemplates.Models.Page
#using (Html.BeginForm()) {
#Html.EditorForModel(Model)
<p><input type="submit" value="Save" /></p>
}
Interestingly, if I use EditorFor on Edit.cshtml then Html.cshtml is actually rendered. e.g.
#Html.EditorFor(model => model.Content)
UPDATE: If I delete object.cshtml then Html.cshtml is also rendered correctly. So this does seem to be an issue in Object.cshtml. It just seems odd that it works on one view but not another
I fixed by explicitly setting the template in Object.cshtml
#Html.Editor(prop.PropertyName, prop.TemplateHint ?? prop.DataTypeName)
Still not clear why it previously worked in one view but not the other though.

Model values are null during [HttpPost]

I'm having some problems with my code and was hoping someone could give me a hand. Here's the snippet I'm working with:
[Authorize]
public ActionResult EventResults(int id)
{
List<Event> CompetitionEvents = Event.getEventsByCompetitionId(id);
ViewBag.CompetitionEvents = CompetitionEvents;
List<Person> Competitors = Competition.getCompetitorsByCompetitionID(id);
ViewBag.Competitors = Competitors;
List<Results> Results = Competition.getCompetitorResultsPairings(CompetitionEvents, Competitors);
ViewBag.Results = Results;
ViewBag.OrganizerEmail = Competition.getCompetitionById(id).OrganizerEmail;
return View();
}
#model BINC.Models.Results
#using BINC.Models;
#{
var eventList = ViewBag.CompetitionEvents as List<Event>;
var competitorList = ViewBag.Competitors as List<Person>;
var resultList = ViewBag.Results as List<Results>;
}
<h2></h2>
<p>Results:</p>
#using (Html.BeginForm())
{
foreach (var evt in eventList)
{
<fieldset>
<legend>#evt.activity.Name</legend>
<p>Event Description: #evt.activity.Description</p>
#foreach (var competitor in competitorList)
{
foreach (var result in resultList)
{
if (result.EventID == evt.id && result.CompetitorEmail == competitor.Email)
{
<p>Competitor: #competitor.FirstName #competitor.LastName</p>
<p>Score: #result.Score</p>
if (ViewBag.OrganizerEmail.Equals(#User.Identity.Name))
{
#Html.LabelFor(model => model.Score, "New Score ");
#Html.TextBoxFor(model => model.Score, new { maxlength = 10, style = "width:125px" })
<input type="submit" name="submitButton" value="Update" />
}
}
}
}
</fieldset>
}
}
[HttpPost]
public ActionResult EventResults(Results res)
{
//stuff
}
My problem is nothing other than the score is set on my Results object.
For example, when I put the value '15' into the text box and click 'Update', I'm passing the Result model object to the httppost method, which has everything set to null other than the 'score' field that I just entered.
Am I over complicating this? Is there an easier way?
I tried adding
#Html.HiddenFor(model => model.EventID);
#Html.HiddenFor(model => model.CompetitorEmail);
but that didn't seem to help any.
You are having multiple Submit buttons and that could be the issue, also this is not considered as good practise
<input type="submit" name="submitButton" value="Update" />
keep just one submit button at the end of the form
Basically-- make sure you pass the model to view-- and use the Html Helpers (ie TextBoxFor() and HiddenFor)
I don't think it's an issue with the submit button-- but the one thing that would probably help is to actually pass the model to the view. You are using the ViewBag to pass your data. Pass the model to View and your Html Helpers should generate the correct form names in order for the model binding to work.

Resources