如何从ModelView加载属性 [英] How to load property from ModelView

查看:66
本文介绍了如何从ModelView加载属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,



我有一个模型userProfile和一个modelview:ImageUploadModel。以及包含三个选项卡的编辑视图。但是在tab2中我想上传一张照片,但后来我想在ModelView中使用这个属性。



模型用户配置文件:



 [显示(名称=  能够聊天时骑)] 
public string AbleToChatWhileRiding {获得; set ; }
[显示(名称= 电话号码)]
public string PhoneNumber { get ; set ; }


[列(TypeName = image) ]


[DisplayName( 文件)]
public byte [] file { get ; set ; }




[显示(名称= 显示个人资料图片)]
public bool DisplayItem {获得; set ; }

[DisplayName( ImageMimeType)]
< span class =code-keyword> public
string ImageMimeType { get ; set ; }

public virtual ICollection< LolaBikePhoto> LolaBikePhotos { get ; set ; }





和modelVIew:



  public   class  ImageUploadModel 
{
[必需(ErrorMessage = 请上传文件)]
[显示(名称= 上传文件)]
[ValidateFile]
public HttpPostedFileBase文件{ get ; set ; }
}


public class ValidateFileAttribute: RequiredAttribute
{

public override bool IsValid( object value
{
int MaxContentLength = 1024 * 1024 * 3 ; // 3 MB
string [] AllowedFileExtensions = new string [] { 。jpg 。gif 。png};

var file = value as HttpPostedFileBase;

if (file == null
返回 false ;
else if (!AllowedFileExtensions.Contains(file.FileName.Substring(file.FileName。 LastIndexOf(' 。'))))
{
ErrorMessage = 请上传您的照片类型: + string .Join( ,AllowedFileExtensions);
return false ;
}
else if (file.ContentLength > MaxContentLength)
{
ErrorMessage = 您的照片是太大,允许的最大大小为: +(MaxContentLength / 1024 )。ToString()+ MB;
return false ;
}
else
return ;
}

}





和视图(tab1的一部分):



 @ model ContosoUniversity.Models.UserProfile 
@using ContosoUniversity.Source
@ {
ViewBag.Title = 编辑;
}

< h2>编辑< / h2 >


< div id = tabs >

< ul>
< li>< a href = #tabs-1>个人信息< / a > < span class =code-keyword>< / li >
< li>< a href = #tabs-2>个人资料照片< / a > < / li >
< li>< a href = #tabs-3>其他照片< / a > < / li >
< / ul >

< div id = tabs-1 > ;
hoi

@using(Html.BeginForm( 编辑 帐户,FormMethod.Post, new {enctype = multipart / form-data}))
{
@ Html.AntiForgeryToken()

< div class = form-horizo​​ntal >
< h4> Lola Biker < / h4 >
< hr />
@ Html.ValidationSummary( true
@ Html.HiddenFor(model = > model.Id)





@ Html.ActionLink( 更改密码 管理


< div class = form-group >
@ Html.LabelFor(m = > m.UserName, new {@class = control-label col-xs-2})
@ Html.TextBoxFor(m = > m。 UserName, new {@class = form-control,style = < span class =code-string> width:250px;})
< / div >



< div class = form-group >
@ Html.LabelFor(m = > m.Email, new {@class = control-label col-xs-2})
@ Html.TextBoxFor(m = > m.Email, new {@class = form-control,style = width:250px;})
< / div >

< div class = form-group >
@ Html.LabelFor(m = > m.FirstName, new {@class = control-label col-xs-2})
@ Html.TextBoxFor(m = > m.FirstName, new {@class = form-control,style = width:250px;})
< / div >

< ; div class = form-group >
@ Html.LabelFor(m = > m.LastName, new {@class = control-label col-xs-2 })
@ Html.TextBoxFor(m = > m.LastName, new {@class = form-control,style = width:250px;})
< / div >






和查看:tab2(tab2的一部分):



< pre lang =c#>< div id = upload-choices >
< div class = < span class =code-string> editor-label >

< div class = lifile >
@ Html.ValidationMessageFor(m = > m.file)
@ * @ Html.ValidationSummary(< span class =code-keyword> true )* @

< / DIV < span class =code-keyword>>

< / div >
< / div >





但是:< br $>


< div  class  =   lifile >  
@ Html.ValidationMessageFor(m = > m.file)
@ * @ Html.ValidationSummary( true )* @

< / div > ;





然后我想使用:m =>来自modelVIew的m.file:

  public  HttpPostedFileBase文件{获得;  set ; } 





而不是模型中的属性:UserProfile。



但是怎么做?



谢谢

解决方案

你应该创建一个类通常它说是Viewmodel。你想在一个视图中显示的属性合并到一个类。



< pre lang =c#> public class YourViewModel {
// 放置两个类的所有属性
[显示(名称= 能够在骑行时聊天)]
public string AbleToChatWhileRiding { get ; set ; }
[显示(名称= 电话号码)]
public string PhoneNumber { get ; set ; }


[列(TypeName = image) ]

// 重命名相同的属性名称,否则会导致编译错误
[DisplayName( 文件)]
public byte [] UserProfilefile { get ; set ; }




[显示(名称= 显示个人资料图片)]
public bool DisplayItem {获得; set ; }

[DisplayName( ImageMimeType)]
< span class =code-keyword> public
string ImageMimeType { get ; set ; }

public virtual ICollection< lolabikephoto> LolaBikePhotos { get ; set ; }
[必需(ErrorMessage = 请上传文件)]
[显示(名称= 上传文件)]
[ValidateFile]
< span class =code-keyword> public HttpPostedFileBase file { get ; set ; }

} < / lolabikephoto >



此外,您应该将视图返回模型更改为新的ViewModel类。

 @model YourViewModel 
@using ContosoUniversity.Source
@ {
ViewBag.Title =Edit;
}





//现在你可以从这个视图访问这两个文件



希望这有帮助


感谢Jameel的反感软件。是的,但它几乎是一个重复的类,因为在新的ModelView类中,所有相同的专业形式UserProfile也出现在新的modelView中。并且只有



 [必需(ErrorMessage =  请上传文件)] 
[显示(名称= 上传文件)]
[ValidateFile]
public HttpPostedFileBase文件{ get < /跨度>; set ; }





然后是新型号的新品。



但是那个还好吗?


Hi everybody,

I have a model userProfile and a modelview: ImageUploadModel. and an edit view with three tabs. But in tab2 I want to upload a photo, but then I want to use the propertie in the ModelView.

the model userprofile:

[Display(Name = "Able to chat while riding")]
        public string AbleToChatWhileRiding { get; set; }
        [Display(Name = "Phone number")]
        public string PhoneNumber { get; set; }


        [Column(TypeName = "image")]


        [DisplayName("File")]       
        public byte[] file { get; set; }


        

        [Display(Name = "Display profile Image")]
        public bool DisplayItem { get; set; }

        [DisplayName("ImageMimeType")]
        public string ImageMimeType { get; set; }

        public virtual ICollection<LolaBikePhoto> LolaBikePhotos { get; set; }



and the modelVIew:

public class ImageUploadModel
   {
       [Required(ErrorMessage = "Please Upload File")]
       [Display(Name = "Upload File")]
       [ValidateFile]
       public HttpPostedFileBase file { get; set; }
   }


   public class ValidateFileAttribute : RequiredAttribute
   {

       public override bool IsValid(object value)
       {
           int MaxContentLength = 1024 * 1024 * 3; //3 MB
           string[] AllowedFileExtensions = new string[] { ".jpg", ".gif", ".png" };

           var file = value as HttpPostedFileBase;

           if (file == null)
               return false;
           else if (!AllowedFileExtensions.Contains(file.FileName.Substring(file.FileName.LastIndexOf('.'))))
           {
               ErrorMessage = "Please upload Your Photo of type: " + string.Join(", ", AllowedFileExtensions);
               return false;
           }
           else if (file.ContentLength > MaxContentLength)
           {
               ErrorMessage = "Your Photo is too large, maximum allowed size is : " + (MaxContentLength / 1024).ToString() + "MB";
               return false;
           }
           else
               return true;
       }

   }



And the view(part of tab1):

@model ContosoUniversity.Models.UserProfile
@using ContosoUniversity.Source
@{
    ViewBag.Title = "Edit";
}

<h2>EDIT</h2>


<div id="tabs">

    <ul>
        <li><a href="#tabs-1">Personal information</a></li>
        <li><a href="#tabs-2">Profile Photo</a></li>
        <li><a href="#tabs-3">Other Photos</a></li>
    </ul>

    <div id="tabs-1">
        hoi

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

            <div class="form-horizontal">
                <h4>Lola Biker</h4>
                <hr />
                @Html.ValidationSummary(true)
                @Html.HiddenFor(model => model.Id)





                @Html.ActionLink("Change your password", "Manage")


                <div class="form-group">
                    @Html.LabelFor(m => m.UserName, new { @class = "control-label col-xs-2" })
                    @Html.TextBoxFor(m => m.UserName, new { @class = "form-control", style = "width: 250px;" })
                </div>



                <div class="form-group">
                    @Html.LabelFor(m => m.Email, new { @class = "control-label col-xs-2" })
                    @Html.TextBoxFor(m => m.Email, new { @class = "form-control", style = "width: 250px;" })
                </div>

                <div class="form-group ">
                    @Html.LabelFor(m => m.FirstName, new { @class = "control-label col-xs-2" })
                    @Html.TextBoxFor(m => m.FirstName, new { @class = "form-control", style = "width: 250px;" })
                </div>

                <div class=" form-group">
                    @Html.LabelFor(m => m.LastName, new { @class = "control-label col-xs-2" })
                    @Html.TextBoxFor(m => m.LastName, new { @class = "form-control", style = "width: 250px;" })
                </div>




and view: tab2(part of tab2):

<div id="upload-choices">
                        <div class="editor-label">
                           
                            <div class="lifile">
                                @Html.ValidationMessageFor(m=> m.file)
                                @*@Html.ValidationSummary(true)*@

                            </div>
                       
                    </div>
                  </div>



But so:

<div class="lifile">
                                @Html.ValidationMessageFor(m=> m.file)
                                @*@Html.ValidationSummary(true)*@

                            </div>



then I want to use: m=>m.file from the modelVIew:

public HttpPostedFileBase file { get; set; }



and not the propertie from the model: UserProfile.

But how to do that?

Thank you

解决方案

You should create one more class Normally it say's Viewmodel .Whatever the properties you want to display in one view merge to one class.

public class YourViewModel{
//put all the properties from both classes
[Display(Name = "Able to chat while riding")]
        public string AbleToChatWhileRiding { get; set; }
        [Display(Name = "Phone number")]
        public string PhoneNumber { get; set; }
 

        [Column(TypeName = "image")]
 
//Renaming the same property name otherwise it makes compile error
        [DisplayName("File")]       
        public byte[] UserProfilefile { get; set; }
 

        
 
        [Display(Name = "Display profile Image")]
        public bool DisplayItem { get; set; }
 
        [DisplayName("ImageMimeType")]
        public string ImageMimeType { get; set; }
 
        public virtual ICollection<lolabikephoto> LolaBikePhotos { get; set; }
 [Required(ErrorMessage = "Please Upload File")]
        [Display(Name = "Upload File")]
        [ValidateFile]
        public HttpPostedFileBase file { get; set; }

}</lolabikephoto>


Also you should change view return model to your new ViewModel class.

@model YourViewModel
@using ContosoUniversity.Source
@{
    ViewBag.Title = "Edit";
}



//now you can access both file from this view

Hope this helps


Thank you Jameel for your answare. yes, but then it is almost a duplicate class, because in the new ModelView class all the same prooperties form UserProfile also comes then in the new modelView. And only

[Required(ErrorMessage = "Please Upload File")]
        [Display(Name = "Upload File")]
        [ValidateFile]
        public HttpPostedFileBase file { get; set; }



is then new in the new modelVIew.

But that is ok?


这篇关于如何从ModelView加载属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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