无法首先使用代码将imageurl上传到viewmodel [英] Unable to upload imageurl to viewmodel using code first

查看:101
本文介绍了无法首先使用代码将imageurl上传到viewmodel的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



您好我先使用代码。上传图像时,它会向控制器返回空值。



这是我的班级文件


 使用系统; 
使用 System.Collections.Generic;
使用 System.Linq;
使用 System.Web;
使用 System.ComponentModel.DataAnnotations;

命名空间 MVC.Model
{
public class 图片
{
public int PhotoId { get ; set ; }
public int UserId { get ; set ; }
public string PhotoCategory { get ; set ; }
public string PhotoUrl { get ; set ; }
public string PhotoName { get ; set ; }
public virtual ICollection< User>用户{获取; set ; }
}
}



ViewModel

 使用系统; 
使用 System.Collections.Generic;
使用 System.ComponentModel.DataAnnotations;
使用 System.Linq;
使用 System.Web;

namespace MVC.Web.ViewModels
{
public PhotoFormModel
{
public int PhotoId { get ; set ; }
[必需(ErrorMessage = 照片名称必填)]
< span class =code-comment> // [显示(名称=电影名称)]
public string PhotoName { get ; set ; }
[必需(ErrorMessage = 上传照片)]
public IEnumerable< HttpPostedFileBase> PhotoUrl { get ; set ; }
public string PhotoCategory { get ; set ; }
}
}





控制器



 [HttpPost] 
[ValidateAntiForgeryToken]
public ActionResult Save(PhotoFormModel表单) ,HttpPostedFileBase文件)
{
if (file!= null
{
string pic = System.IO.Path.GetFileName(file.FileName);
// string path = System.IO.Path.Combine(
< span class =code-comment> // Server.MapPath(〜/ Photos /),pic);
/// / file已上传
// file.SaveAs(path);
string ImageName = System.IO.Path .GetFileName(file.FileName);
string physicalPath = Server.MapPath( 〜/ images / + ImageName);

// 将图像保存在文件夹中
file.SaveAs( physicalPath);

// 保存图像路径到数据库的路径,或者你可以发送图像
// 直接到数据库
// 如果你想存储byte [] ie的话。 for DB
使用(MemoryStream ms = new MemoryStream())
{
file.InputStream.CopyTo(ms);
byte [] array = ms.GetBuffer();
}

}
// if(ModelState.IsValid)
if (ModelState.ContainsKey( {key}))
ModelState [ {key}] Errors.Clear();
{
Mapper.CreateMap< PhotoFormModel,CreateOrUpdatePhotoCommand>();
var command = Mapper.Map< PhotoFormModel,CreateOrUpdatePhotoCommand>(form);
IEnumerable< ValidationResult> errors = commandBus.Validate(command);
// ModelState.AddModelErrors(errors);
if (ModelState.IsValid)
{
var result = commandBus.Submit(command);
if (result.Success) return RedirectToAction( 索引);
}
}
// 如果失败
if (form.PhotoId == 0
return 查看( 创建,表格);
else
return 查看( 编辑,表格);
}





Create.cshtml

 @ model MVC.Web.ViewModels.PhotoFormModel 
@ {
ViewBag.Title = 创建;
}
< h2>创建< / h2 >
@using(Html.BeginForm( Save 照片,FormMethod.Post,
new {enctype = multipart / form-data}) )
{
@ Html.AntiForgeryToken()
@ Html.ValidationSummary( true
< fieldset>
< legend>事件< / 图例 >

< div class = < span class =code-string> editor-label
>
@ Html.LabelFor(model = > model.PhotoCategory)
< / div >
< div class = editor-field >
@ Html.EditorFor(model = < span class =code-keyword>> model.PhotoCategory)
@ Html.ValidationMessageFor(model = > model.PhotoCategory)
< / div >

< ; div class = editor-label >
@ Html.LabelFor(model = > model.PhotoName)
< / div >
< div class = editor-字段 >
@ Html.EditorFor(model = > 型号.PhotoName)
@ Html.ValidationMessageFor(model = > model.PhotoName)
< / div >
< div = < span class =code-string> editor-label >
@ Html.LabelFor(model = > model.PhotoUrl)
< / div >
< div class = editor-field >
< input type = file name = file id = file style = width:100%; />
< input type = submit = 上传 class = submit /> @ Html.ValidationMessageFor(model = > model.PhotoUrl)
< / div >
< / fieldset >
}
< div>
@ Html.ActionLink( 返回列表 索引
< / div >





问题在于保存操作viewmodel显示图像url的空值但文件对象显示url值

解决方案

Sindhu,



 @ Html.LabelFor(model = >  model.PhotoUrl)





不会将值发送回控制器。



添加一个隐藏字段,它应该工作< br $>


 @ Html.HiddenFor(model = >  model.PhotoUrl) 



Hi i am using code first. It returning null value to controller when uploading image.

Here is my class file

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;

namespace MVC.Model
{
    public class Photo
    {
        public int PhotoId { get; set; }
        public int UserId { get; set; }
        public string PhotoCategory { get; set; }
        public string PhotoUrl { get; set; }
        public string PhotoName { get; set; }
        public virtual ICollection<User> Users { get; set; }
    }
}


ViewModel

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;

namespace MVC.Web.ViewModels
{
    public class PhotoFormModel
    {
        public int PhotoId { get; set; }
        [Required(ErrorMessage = "Photo Name Required")]
        //[Display(Name = "Movie Name")]
        public string PhotoName { get; set; }
        [Required(ErrorMessage = "Upload Photo")]
        public IEnumerable<HttpPostedFileBase> PhotoUrl { get; set; }
        public string PhotoCategory { get; set; }
    }
}



Controller

[HttpPost]
       [ValidateAntiForgeryToken]
       public ActionResult Save(PhotoFormModel form,HttpPostedFileBase file)
       {
           if (file != null)
           {
               string pic = System.IO.Path.GetFileName(file.FileName);
               //string path = System.IO.Path.Combine(
               //                       Server.MapPath("~/Photos/"), pic);
               //// file is uploaded
               //file.SaveAs(path);
               string ImageName = System.IO.Path.GetFileName(file.FileName);
               string physicalPath = Server.MapPath("~/images/" + ImageName);

               // save image in folder
               file.SaveAs(physicalPath);

               // save the image path path to the database or you can send image
               // directly to database
               // in-case if you want to store byte[] ie. for DB
               using (MemoryStream ms = new MemoryStream())
               {
                   file.InputStream.CopyTo(ms);
                   byte[] array = ms.GetBuffer();
               }

           }
           //if (ModelState.IsValid)
           if (ModelState.ContainsKey("{key}"))
               ModelState["{key}"].Errors.Clear();
           {
               Mapper.CreateMap<PhotoFormModel, CreateOrUpdatePhotoCommand>();
               var command = Mapper.Map<PhotoFormModel, CreateOrUpdatePhotoCommand>(form);
               IEnumerable<ValidationResult> errors = commandBus.Validate(command);
               //ModelState.AddModelErrors(errors);
               if (ModelState.IsValid)
               {
                   var result = commandBus.Submit(command);
                   if (result.Success) return RedirectToAction("Index");
               }
           }
           //if fail
           if (form.PhotoId == 0)
               return View("Create", form);
           else
               return View("Edit", form);
       }



Create.cshtml

@model MVC.Web.ViewModels.PhotoFormModel
@{
    ViewBag.Title = "Create";
}
<h2>Create</h2>
@using (Html.BeginForm("Save", "Photo", FormMethod.Post,
                            new { enctype = "multipart/form-data" }))
{
    @Html.AntiForgeryToken()
    @Html.ValidationSummary(true)
    <fieldset>
        <legend>Event</legend>     

<div class="editor-label">
            @Html.LabelFor(model => model.PhotoCategory)
        </div> 
        <div class="editor-field">
            @Html.EditorFor(model => model.PhotoCategory)
            @Html.ValidationMessageFor(model => model.PhotoCategory)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.PhotoName)
        </div>
        <div class="editor-field">
             @Html.EditorFor(model => model.PhotoName)
            @Html.ValidationMessageFor(model => model.PhotoName)
</div>
<div class="editor-label">
            @Html.LabelFor(model => model.PhotoUrl)
        </div>
        <div class="editor-field">
         <input type="file" name="file" id="file" style="width: 100%;" /> 
    <input type="submit" value="Upload" class="submit" />             @Html.ValidationMessageFor(model => model.PhotoUrl)
</div>
    </fieldset>
}
<div>
    @Html.ActionLink("Back to List", "Index")
</div>



Problem is in save action viewmodel showing null value for image url but file object is showing url value

解决方案

Sindhu,

@Html.LabelFor(model => model.PhotoUrl)



Will not send the value to back to controller.

Add a hidden field for the same and it should work

@Html.HiddenFor(model => model.PhotoUrl)


这篇关于无法首先使用代码将imageurl上传到viewmodel的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆