2012-12-20 12 views
11

जब मैं सबमिट करता हूं, file पैरामीटर शून्य है।फॉर्म सबमिट होने पर मॉडल शून्य है

@model MyProject.Controllers.Admin.FileViewModel 

@{ 
    ViewBag.Title = "Create"; 
    Layout = "~/Views/Shared/_BackOfficeLayout.cshtml"; 
} 

@using (Html.BeginForm("Create", "Files", FormMethod.Post, new { enctype = "multipart/form-data" })) 
{ 
    <fieldset> 
    <legend>Create</legend> 

    <div class="editor-label"> 
     @Html.LabelFor(model => model.File) 
    </div> 
    <div class="editor-field"> 
     @Html.TextBoxFor(model => model.File, new { type = "file" }) 
     @Html.ValidationMessageFor(model => model.File) 
    </div> 

    <p> 
     <input type="submit" value="Create" /> 
    </p> 
    </fieldset> 
} 

<div> 
    @Html.ActionLink("Back to List", "Index") 
</div> 

उत्तर

37

यह संघर्ष और बांधने की मशीन फ़ाइल नाम के साथ FileViewModel वस्तु को अपने फ़ाइल संपत्ति के लिए बाध्य करने की कोशिश कर नामकरण है, यही कारण है कि आप अशक्त प्राप्त होते हैं:

public ActionResult Create() 
{ 
    return View(new FileViewModel()); 
} 

[HttpPost]  
[InitializeBlobHelper] 
public ActionResult Create(FileViewModel file) 
{ 
    if (ModelState.IsValid) 
    { 
    //upload file 
    } 
    else 
    return View(file); 
} 

public class FileViewModel 
{ 
    internal const string UploadingUserNameKey = "UserName"; 
    internal const string FileNameKey = "FileName"; 

    internal const string Folder = "files"; 

    private readonly Guid guid = Guid.NewGuid(); 

    public string FileName 
    { 
    get 
    { 
     if (File == null) 
     return null; 
     var folder = Folder; 
     return string.Format("{0}/{1}{2}", folder, guid, Path.GetExtension(File.FileName)).ToLowerInvariant(); 
    } 
    } 

    [RequiredValue] 
    public HttpPostedFileBase File { get; set; } 
} 

यहाँ cshtml है। पोस्ट नाम केस असंवेदनशील हैं।

बदलें:

public ActionResult Create(FileViewModel file) 

करने के लिए:

public ActionResult Create(FileViewModel model) 

या किसी अन्य नाम

+0

शियाट! मुझे विश्वास नहीं था कि यह काम करेगा लेकिन ऐसा हुआ। ऐसा क्यों हुआ? – Shimmy

+4

@Shimmy यह 'फ़ाइल' नाम के साथ 'FileViewModel' ऑब्जेक्ट में' फ़ाइल' प्रॉपर्टी को बाध्य करने का प्रयास करने वाला संघर्ष और बाइंडर नाम दे रहा है, यही कारण है कि आपको 'शून्य' मिलता है। पोस्ट नाम केस असंवेदनशील हैं। – webdeveloper

+1

आप अच्छे आदमी हैं! अच्छी पकड़! – Shimmy

1

यह मेरी मुद्दे के रूप में अच्छी तरह से हल करने के लिए। यह एक ऐसा नाम था जिसका उपयोग मैं मॉडल के समान था, जो वैरिएबल के समान था जिसे मैंने पोस्ट मॉडल भी सौंपा था। एक बार जब मैंने फ़ील्ड नाम को हल किया तो सभी उम्मीद के अनुसार काम करते थे।

बेशक त्रुटि यह इंगित करने में सहायक नहीं थी।

संबंधित मुद्दे