无法访问变量以保存在数据库中

时间:2016-05-31 18:33:50

标签: c# asp.net asp.net-mvc entity-framework entity-framework-6

我正在做一个扩展方法,我希望变量image等于我的图片名称

扩展方法:

 public async Task<string> CreateNewSlider(Slider slider, HttpPostedFileBase file) // file always return null
    {
        string pic = null;
        if (file != null)
        {
            pic = System.IO.Path.GetFileName(file.FileName);
            string path = System.IO.Path.Combine(
                                   System.Web.HttpContext.Current.Server.MapPath("~/Content/images/slider"), pic);
            file.SaveAs(path);

            using (var ms = new MemoryStream())
            {
                file.InputStream.CopyTo(ms);
                byte[] array = ms.GetBuffer();
            }
        }
        try
        {
            var createnewslider = new Slider
            {
                Alt = slider.Alt,
                CreationDate = slider.CreationDate,
                Description = slider.Description,
                IsVisible = slider.IsVisible,
                Order = slider.Order,
                Subtitle = slider.Subtitle,
                Title = slider.Title,
                VideoLink = slider.VideoLink,
                Image = pic
            };
            db.SlidersList.Add(createnewslider);
            await db.SaveChangesAsync();
            return "Slider Photo " + file + "has been created successfull";

        }
        catch (Exception ex)
        {
            return ex.InnerException.Message + "Contact to administrator";
        }

    }

如何访问我的变量pic并最终发布到我的模型中

注意:“图像变量是类型字符串”

----------------------编辑----------------------

我在尝试创建新滑块时遇到问题,我想创建它并将图像存储到数据库中的图像变量

型号:

public class Slider
{
    public int SliderId { get; set; }
    public int MainPageId { get; set; }
    public MainPage MainPage { get; set; }
    public string Title { get; set; }
    public string Order { get; set; }
    public string Subtitle { get; set; }
    public string Description { get; set; }
    public string Image { get; set; }
    public string Alt { get; set; }
    public string VideoLink { get; set; }
    public DateTime CreationDate { get; set; }
    public bool IsVisible { get; set; }
}

创建视图:

@model xxx.Models.Slider

@{
ViewBag.Title = "Create";
}

<h2>Create</h2>

 @using (Html.BeginForm()) 
 {
@Html.AntiForgeryToken()

<div class="form-horizontal">
    <h4>Slider</h4>
    <hr />
    @Html.ValidationSummary(true, "", new { @class = "text-danger" })


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

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

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

    <div class="form-group">
        @Html.LabelFor(model => model.Description, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.Description, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.Description, "", 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">
           @using (Html.BeginForm("Create", "Slider", FormMethod.Post,
                        new { enctype = "multipart/form-data" }))
           {
            <label for="file">Subir imágen:</label>
            <input type="file" name="file" id="file" style="width: 100%;" />
           }
        </div>
    </div>

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

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

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

    <div class="form-group">
        @Html.LabelFor(model => model.IsVisible, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            <div class="checkbox">
                @Html.EditorFor(model => model.IsVisible)
                @Html.ValidationMessageFor(model => model.IsVisible, "", new { @class = "text-danger" })
            </div>
        </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>

在扩展方法中,它传递以捕获异常并将其返回

我使用调试模式,文件变量总是为null但我不知道为什么

2 个答案:

答案 0 :(得分:0)

这是因为image/svg+xml对象范围内的pic不可用。只需在if语句之外声明createnewslider变量:

pic

在映射到string pic = string.Empty; if (file != null) { pic = System.IO.Path.GetFileName(file.FileName); string path = System.IO.Path.Combine( HostingEnvironment.MapPath("~/Content/images/slider"), pic); file.SaveAs(path); using (MemoryStream ms = new MemoryStream()) { file.InputStream.CopyTo(ms); byte[] array = ms.GetBuffer(); } } var createnewslider = new Slider { Alt = slider.Alt, CreationDate = slider.CreationDate, Description = slider.Description, IsVisible = slider.IsVisible, Order = slider.Order, Subtitle = slider.Subtitle, Title = slider.Title, VideoLink = slider.VideoLink, Image = pic }; 之前检查内容。

答案 1 :(得分:0)

在与构造函数相同的范围内定义它,以便构造函数可以访问它。

public async Task<string> CreateNewSlider(Slider slider, HttpPostedFileBase file)
{
    string pic = null;
    if (file != null)
    {
        pic = System.IO.Path.GetFileName(file.FileName);
        string path = System.IO.Path.Combine(
                               HostingEnvironment.MapPath("~/Content/images/slider"), pic);
        file.SaveAs(path);

        using (MemoryStream ms = new MemoryStream())
        {
            file.InputStream.CopyTo(ms);
            byte[] array = ms.GetBuffer();
        }
    }
    var createnewslider = new Slider
    {
        Alt = slider.Alt,
        CreationDate = slider.CreationDate,
        Description = slider.Description,
        IsVisible = slider.IsVisible,
        Order = slider.Order,
        Subtitle = slider.Subtitle,
        Title = slider.Title,
        VideoLink = slider.VideoLink,
        Image = pic // I can´t access to pic variable 

    };
    db.SlidersList.Add(createnewslider);
    await db.SaveChangesAsync();
    return "Slider Photo " + file + "has been created";

}