MVC4 NULL Reference Exception was unhandle by user - asp.net-mvc

"Object reference not set to an instance of an object."
[HttpPost]
public ActionResult Create(AdulLiteracyTeachers adulliteracyteachers, HttpPostedFileBase[] files)
{
foreach (HttpPostedFileBase file in files)
{
string path = System.IO.Path.Combine(Server.MapPath("~/App_Data"), System.IO.Path.GetFileName(file.FileName));
file.SaveAs(path);
}
if (ModelState.IsValid)
{
db.AdulLiteracyTeachers.Add(adulliteracyteachers);
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.DistID = new SelectList(db.Districts, "DistID", "DistName", adulliteracyteachers.DistID);
return View(adulliteracyteachers);
}
here is my view :
<p>
<label for="file">Upload Image:</label>
<input type="file" name="files" value="" multiple="multiple"/>
<input name="Upload" type="submit" value="Create" />
</p>
On create button I got this error in MVC 4

Related

I have a question how to add input fields values with same name into the database using entity framework? Below is my code,

This is my HomeWithIndentityController
namespace MVC.CRUDDynamicFormTest.Controllers
{
public class HomeWithIndentityController : Controller
{
// GET: HomeWithIndentity
public ActionResult WithIndex()
{
return View();
}
public ActionResult GetData()
{
using (DynamicCRUDDatabase2Entities db = new DynamicCRUDDatabase2Entities())
{
List<DynamicCRUDTable2> dynamicCRUDTable2s = db.DynamicCRUDTable2.ToList<DynamicCRUDTable2>();
return Json(new { data = dynamicCRUDTable2s }, JsonRequestBehavior.AllowGet);
}
}
[HttpGet]
public ActionResult Add(int id = 0)
{
return View(new DynamicCRUDTable2());
}
[HttpPost]
public ActionResult Add(DynamicCRUDTable2 obj)
{
using (DynamicCRUDDatabase2Entities db = new DynamicCRUDDatabase2Entities())
{
db.DynamicCRUDTable2.Add(obj);
db.SaveChanges();
return Json(new { succces = true, message = "saved Successfully" }, JsonRequestBehavior.AllowGet);
//return RedirectToAction("Index", "Home");
}
}
}
}
this is my entity model class
public partial class DynamicCRUDTable2
{
public int Id { get; set; }
public string FirstName { get; set; }
}
This my View
<form action="~/HomeWithIndentity/Add" method="POST" onsubmit="return Submitform(this)">
<input data-val="true" id="Id" name="Id" type="hidden" />
<label>First Name</label>
<input type="text" name="FirstName[]" class="form-control" />
<input type="text" name="FirstName[]" class="form-control" />
<br />
<br />
<div>
<input type="submit" value="Submit" class="btn btn-success" />
<input type="reset" value="Reset" class="btn btn-danger" />
<a class="btn btn-danger" href="~/Home/Index">Cancel</a>
</div>
</form>
In the above view i want to add the firstname input field values to the Database dynamicallly.but it does not working can you let me know why?What errors i have done.
does anyone know how to do that?

mvc passing data from view to controller

My Controller
public class OgrenciController : Controller
{
[HttpPost]
public ActionResult home(int perId)
{
if(perId=="anything")
{
//something
}
return View();
}
}
This is my view
#foreach (var item in Model)
{
siraNo++;
<form method="post">
<input type="radio" name="perId" value="#item.specialId">
<input type="submit" value="send" />
</form>
}
but in the POST method, perId not take anythings
use something like this.
#using (Html.BeginForm())
{
foreach (var item in Model)
{
<input type="radio" name="perId" value="#item.specialId"><br /><br />
}
<input type="submit" ur value="send" />
}

Multiple Action of Controller in single Button in MVC 4

my controller Have 2 Actions :
[HttpPost]
public ActionResult Upload(HttpPostedFileBase[] files)
{
foreach (HttpPostedFileBase file in files)
{
string path = System.IO.Path.Combine(Server.MapPath("~/App_Data"), System.IO.Path.GetFileName(file.FileName));
file.SaveAs(path);
}
ViewBag.Message = "File(s) uploaded successfully";
return RedirectToAction("Index");
}
//
// GET: /AdultLiteracyTeachers/Details/5
public ActionResult Details(int id = 0)
{
AdulLiteracyTeachers adulliteracyteachers = db.AdulLiteracyTeachers.Find(id);
if (adulliteracyteachers == null)
{
return HttpNotFound();
}
return View(adulliteracyteachers);
}
my view in Create.cshtml
#using (Html.BeginForm(Upload, ControllerName, FormMethod.Post, new { enctype = "multipart/form-data" }))
<input type="file" name="files" value="Upload Image" />
<input name="Upload" type="submit" value="Create" />
Problem is
only upload is working when I submit button others create etc not working
how to call multiple actions in single form create button ?
I believe you can use the beginform multiple times like this:
#using (Html.BeginForm(Upload, ControllerName, FormMethod.Post, new { enctype = "multipart/form-data" })){
<input type="submit" name="files" value="Upload Image" />
}
#using (Html.BeginForm(Details, ControllerName, FormMethod.Post, new { enctype = "multipart/form-data" })){
<input name="Upload" type="submit" value="Create" />
}
and make sure that the button type="submit".

Pass extra parameters along with the HttpPostedFileBase object

In my MVC app, I have an upload View with GET and POST actions.
the question is how can I pass extra data to the POST Action along with the HttpPostedFileBase object, e.g., some ID for example.
You just pass it as an additional parameter
HTML:
<form action="" method="post" enctype="multipart/form-data">
<input type='text' id='txtId' name='id'/>
<input type="file" name="file" id="file" />
<input type="submit" />
</form>
Controller:
[HttpPost]
public ActionResult Upload(HttpPostedFileBase file, string id) {
if (file.ContentLength > 0) {
var fileName = Path.GetFileName(file.FileName);
var path = Path.Combine(Server.MapPath("~/App_Data/uploads"), fileName);
file.SaveAs(path);
}
return RedirectToAction("Index");
}

Stack trace error

I am having the error message:I can`t figure out what is wrong. Can someone help me please. Thanks.
Stack Trace:
[NotSupportedException: Collection is
read-only.]
System.SZArrayHelper.Clear() +56
System.Web.Mvc.CollectionHelpers.ReplaceCollectionImpl(ICollection`1
collection, IEnumerable newContents)
+125
ExecuteStep(IExecutionStep step,
Boolean& completedSynchronously) +184
My code is:
Model:
namespace TestArrays.Models
{
public class Person
{
public CategoriesRow[] Categories { get; set; }
public Person()
{
Categories = new CategoriesRow[1];
Categories[0] = new CategoriesRow();
Categories[0].Name = "Bug";
Categories[0].ID = "0";
}
}
public class CategoriesRow
{
public String Name { get; set; }
public String ID { get; set; }
}
}
Controller
public ActionResult Create()
{
return View(new Person());
}
//
// POST: /Person/Create
[HttpPost]
public ActionResult Create(Person person)
{
try
{
// TODO: Add insert logic here
return RedirectToAction("Index");
}
catch
{
return View();
}
}
Views
<form id="Form" action="<%=Url.Action("Create",new{Action="Create"}) %>" method="post" enctype="multipart/form-data">
<div id="categoriessection" >
<h3>Categories</h3>
<ul class= "list" id="categoryList">
<%if (Model.Categories!=null) {%>
<%int count = 0; %>
<%foreach (var category in Model.Categories)
{%>
<%if (!String.IsNullOrEmpty(category.Name))
{%>
<li><input type="hidden" name="Categories.Index" value="<%=count%>" />
<input type="text" value="<%=category.Name%>" name="Categories[<%=count%>].Name" style="width:280px"/>
<input type="hidden" value="<%=category.ID%>" name="Categories[<%=count++%>].ID" style="width:280px"/>
<input type="button" value = "Delete"/>
</li>
<%}
%>
<%} %>
<%} %>
<li> <input type="hidden" name="Categories.Index" value="value0" />
<input type="text" value="" name="Categories[value0].Name" style="width:280px"/>
<input type="hidden" value="" name="Categories[value0].ID" style="width:280px"/>
<input type="button" value= "Add" />
</li>
</ul>
</div>
<div>
<input type ="submit" value="Save" id="save" />
</div>
</form>
I usually use lists instead of vectors in models:
public List<CategoriesRow> Categories { get; set; }

Resources