I am new to MVC. I am using MVC 5.
I have created 2 controllers with GET and POST, namely AddStories.
What I want to do is that I post data and then return a list of data to view and then loop it over and display.
The 1st part such as posting data works perfectly but not the second part. It throws an error:
Object reference not set to an instance of an object.
Code:
Controller:
[HttpGet]
public ActionResult AddStories()
{
return View();
}
[HttpPost]
//[Bind("")]
public ActionResult AddStories(Stories st, HttpPostedFileBase files)
{
try
{
basicoperations bo = new basicoperations();
if (files != null)
{
string filePath = Path.Combine(Server.MapPath("~/UploadedFiles/"), Path.GetFileName(files.FileName));
files.SaveAs(filePath);
}
st.Image = Path.GetFileName(files.FileName);
if (bo.insertImages(st))
{
ViewBag.Data = "Added";
List listofStories = new List();
listofStories = bo.GetAllImages();
ViewBag.Grid = listofStories;
}
else
{
return View("AddStories");
}
}
catch (Exception ex)
{
ViewBag.Data = ex.Message;
}
return View("AddStories");
}
View:
@model HimHer.Models.Stories
@using (Html.BeginForm("AddStories", "Stories", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
@Html.AntiForgeryToken()
Stories
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
@Html.LabelFor(model => model.Story, htmlAttributes: new { @class = "control-label col-md-2" })
@Html.EditorFor(model => model.Story, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Story, "", new { @class = "text-danger" })
@Html.LabelFor(model => model.Image, htmlAttributes: new { @class = "control-label col-md-2" })
}
@*@ViewBag.Data
*@
@{
var listData = (List)ViewBag.Grid;
if (listData.Count > 0)
{
foreach (var item in listData)
{
item.Image
}
}
}
No comments:
Post a Comment