Question

I have a model that looks like:

public class schoolModel
{
    public SelectList Categories;
    public school Entity;


}

where school looks like:

public class school 
{

int? CategoryId{get;set;} // foreingKey
bool IncludeAttached{get;set;}

}

I initialize schoolModel as follows:

var model = new schoolModel();
            model.Entity = schoolServiceAgent.Output.Entities.FirstOrDefault(n => n.Id == id);
            model.Categories = new SelectList(new GenderServiceAgent().GetCategoriesByAlias(null, true), "Id", "Alias", model.Entity.CategoryId);

and I use them like

@Html.DropDownListFor(model => model.Entity.CategoryId, new SelectList(Model.Categories, "Value", "Text"), Model.Entity.CategoryId)
@Html.CheckBoxFor(model => model.Entity.IncludeAttached.Value, new { @class = "form-control placeholder-no-fix", name = "IncludeAttached", @checked = "checked" })

but at the edit post the FormCollection has no value to CategoryId , and IncludeAttached

I try to get them using

public ActionResult Edit(int id, FormCollection collection)
{
    var categoryid = int.Parse(collection["CategoryId"]); 
    var result = selectedschool.inMediaArabicApp = bool.Parse(collection["IncludeAttached"]);

}   

the above raise null exception , any idea how to solve that? the form surrounding the edit looks like

@using (@Html.BeginForm("Edit", "Schools", FormMethod.Post,
                             new { enctype = "multipart/form-data" }))
{
Was it helpful?

Solution

Instead of using FormCollection why don't you use the .Net Model binding capability?

Use [HttpPost] since you are posting from the form.

[HttpPost]
public ActionResult Edit(School model)
{
   var categoryid = model.CategoryId; 
   var result = model.IncludeAttached;

} 

Also, c# conventions are to use Pascal Casing for class names and variables.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top