为什么viewbag发送数据不被查看?

时间:2017-10-16 13:39:42

标签: c# asp.net-mvc c#-4.0 model-view-controller asp.net-mvc-5

我是MVC的新手。我正在使用MVC 5.

我用GET和POST创建了2个控制器,即 AddStories

我想要做的是发布数据,然后返回要查看的数据列表,然后将其循环显示。

第一部分如发布数据完美但不是第二部分。它抛出一个错误:

对象引用未设置为对象的实例。

代码:

控制器:

    [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<Stories> listofStories = new List<Stories>();

                listofStories = bo.GetAllImages();

                ViewBag.Grid = listofStories;


            }
            else
            {
                return View("AddStories");
            }


        }
        catch (Exception ex)
        {
            ViewBag.Data = ex.Message;
        }

        return View("AddStories");
    }

查看:

@model HimHer.Models.Stories



@using (Html.BeginForm("AddStories", "Stories", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    @Html.AntiForgeryToken()

    <div class="form-horizontal">
        <h4>Stories</h4>
        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        <div class="form-group">
            @Html.LabelFor(model => model.Story, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Story, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Story, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.Image, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                <input id="files" class="form-control" name="files" type="file" />
            </div>
        </div>

        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Add" class="btn btn-default" />
            </div>
        </div>
        <div>




        </div>
    </div>
}


<div>
    @*<h3>@ViewBag.Data</h3>*@
    @{
        var listData = (List<HimHer.Models.Stories>)ViewBag.Grid;
        if (listData.Count > 0)
        {
            foreach (var item in listData)
            {
                <h6>item.Image</h6>
            }
        }
    }


</div>

0 个答案:

没有答案