This is a migrated thread and some comments may be shown as answers.

Grid File Upload

14 Answers 555 Views
General Discussions
This is a migrated thread and some comments may be shown as answers.
This question is locked. New answers and comments are not allowed.
Manuel
Top achievements
Rank 1
Manuel asked on 31 Oct 2010, 02:26 PM
Is there a way to add a file upload to the Create and Edits commands in a Grid?

I already created a customized Edit/Create Template, where i added the input field but Request.Files are always empty.

The content type is application/x-www-form-urlencoded but needs to be multipart/form-data is that maybe the reason and how can i change it?

14 Answers, 1 is accepted

Sort by
0
Accepted
Rosen
Telerik team
answered on 01 Nov 2010, 10:56 AM
Hello Manuel,

Unfortunately, the current version of our MVC Grid does not support changing the enctype of the form element generated during editing. However, I'm happy to inform you that we have managed to add such option to the editing settings. I have attached a internal build which does include it. Note that you should modify the grid's declaration to include the following line:

.Editable(editable => editable.FormHtmlAttributes(new { enctype = "multipart/form-data" }))

I have updated your telerik points for bringing this to our attention.

Regards,
Rosen
the Telerik team
Do you want to have your say when we set our development plans? Do you want to know when a feature you care about is added or when a bug fixed? Explore the Telerik Public Issue Tracking system and vote to affect the priority of the items
0
Manuel
Top achievements
Rank 1
answered on 01 Nov 2010, 07:39 PM
Thank you for your resonse. Maybe i've done something wrong but i applied your hotfix and changed the code line but the content type is still "application/x-www-form-urlencoded; charset=UTF-8".
0
Rosen
Telerik team
answered on 02 Nov 2010, 09:09 AM
Hello Manuel,

I have attached a small sample, which demonstrates the scenario in question. Please take a look maybe I'm missing something obvious.

Regards,
Rosen
the Telerik team
Do you want to have your say when we set our development plans? Do you want to know when a feature you care about is added or when a bug fixed? Explore the Telerik Public Issue Tracking system and vote to affect the priority of the items
0
Manuel
Top achievements
Rank 1
answered on 02 Nov 2010, 11:04 AM
Hi, and thank you for your help again i appreciate that.

Yes it was really obvious i had a workaround with a submit form as client template and the grid took the ajax binding instead of the server binding.

Regards Manuel
0
Aaron
Top achievements
Rank 1
answered on 11 Nov 2010, 03:05 PM
One might add that this discussion pertains to file uploads with Server binding only. Uploads with Ajax binding are trickier because the edit form is submitted via JSON-serialization which is incapable of processing the file regardless of the form enctype.

One work-around I found is the jQuery Form plugin's $.ajaxSubmit() method which uses some javascript/iframe voodoo to get the job done. The MVC grid client-side API should provide plenty of hooks to call the upload code.
0
Manuel
Top achievements
Rank 1
answered on 20 Dec 2010, 10:34 AM
Thanks for the hint, i took me some time but here is how i get it to work.

Adding Client Events

.ClientEvents(events => events.OnEdit("onEdit").OnSave("onSave"))


JavaScript Functions

function onEdit(e) {
var mode = e.mode;
if (mode == 'insert') {
       $(
"#DocumentGridform").submit(function (e) {
         
var options = { url: '/Document/_Insert',
          contentType:
'multipart/form-data',
          type:
'POST',            
          success:
function (result) {                  
                 $(
'div[class~="t-grid"]').data('tGrid').ajaxRequest();
          }};     
       $(
this).ajaxSubmit(options);
           
return false;
       });
}

if (mode == 'edit') {
        $(
"#DocumentGridform").submit(function (e) {
           
var options = { url: '/Document/_Update',
            contentType:
'multipart/form-data',
            type:
'POST',
            success:
function (result) {
                  $(
'div[class~="t-grid"]').data('tGrid').ajaxRequest();
            }};          
            $(
this).ajaxSubmit(options);
           
return false;});
}
};

function onSave(e) {
    e.preventDefault();
    $(
"#DocumentGridform").submit();
    $('#DocumentGridPopUp').data('tWindow').center().close();

};

0
James
Top achievements
Rank 1
answered on 17 Jan 2011, 05:45 PM
Hi,

Have you got a working sample of this for InForm mode?

Thanks

James
0
Manuel
Top achievements
Rank 1
answered on 17 Jan 2011, 06:09 PM
Well, i guess it should work in InForm mode too, i can try it tomorrow and give you feedback. Have you defined an editor template for the file upload?
0
James
Top achievements
Rank 1
answered on 17 Jan 2011, 06:53 PM
Hi Manuel,

Thanks for the speedy response. Yes I do have UploadEditor template defined.It would be great if you could try tomorrow the InForm Mode and give me feedback.

Thanks

James
0
Manuel
Top achievements
Rank 1
answered on 18 Jan 2011, 02:40 PM
Hi James,

the inForm mode works for me too, but inLine mode does not. The only thing had to change for InForm mode was changing the grideditmode to InForm. Did you really mean InForm or InLine? Should i post my template code for you?

Regards
Manuel

0
James
Top achievements
Rank 1
answered on 18 Jan 2011, 02:48 PM
Hi Manuel

That would be great, InLine works for me but InForm doesnt, can you include your code, so I can see where I'm going wrong?

Thanks

James

0
Manuel
Top achievements
Rank 1
answered on 18 Jan 2011, 03:33 PM
You should check via breakpoint if your template code is called on page load. Here is my code, it's a little messy, but i hope it helps. Let me know if you need anything else.

Editor Template: "/Shared/EditorTemplates/Object.ascx"

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %>
<% if (ViewData.TemplateInfo.TemplateDepth > 1) { %>
    <%= ViewData.ModelMetadata.SimpleDisplayText %>
<% } else {
     %>
    <table cellpadding="0" cellspacing="2" border="0">
    <% foreach (var prop in ViewData.ModelMetadata.Properties.Where(pm => pm.ShowForEdit && !ViewData.TemplateInfo.Visited(pm))) { %>
        <% if (prop.HideSurroundingHtml) { %>
            <%= Html.Hidden(prop.PropertyName) %>
        <% }
           else
           { %>
            <tr>
                <td>
                    <div class="editor-label" style="text-align: right;">
                        <%= prop.IsRequired ? "*" : "" %>
                        <%= Html.Label(prop.PropertyName) %>
                    </div>
                </td>
                <td>
                    <div class="editor-field">
                        <%
                        if (prop.ModelType.Equals(typeof(byte[])))
                            { %>
                                <input type="file" id="Data" name="File"/>
                                <%= Html.ValidationMessage("File") %>
                           <%}
                        else if (prop.ModelType.Equals(typeof(DateTime)))
                           { %>
                               <%= Html.Telerik().DatePicker()
                                           .Name(prop.PropertyName)
                                           .Value(((DateTime)prop.Model) > DateTime.MinValue ? ((DateTime)prop.Model) : DateTime.Today)
%>
                            <%= Html.ValidationMessage(prop.PropertyName, "*")%>
                            <%
                           }
                        else if (prop.TemplateHint != null && prop.TemplateHint.Equals("TextArea"))
                           { %>
                                <%= Html.TextArea(prop.PropertyName)%>
                                <%= Html.ValidationMessage(prop.PropertyName, "*")%>
                          <%}
                            else
                               { %>
                                <%= Html.Editor(prop.PropertyName)%>
                                <%= Html.ValidationMessage(prop.PropertyName, "*")%>
                            <% } %>
                    </div>
                </td>
            </tr>
        <% } %>
    <% } %>
    </table>
<% } %>

Telerik Grid:

<%= Html.Telerik().Grid<MR.Models.DocumentViewModel>()
        .Name("DocumentGrid")
           .ToolBar(commands=> {
        if (Roles.GetRolesForUser().Contains("Administrators") || Roles.GetRolesForUser().Contains("PowerUsers"))
        { commands.Insert().ButtonType(GridButtonType.ImageAndText);
        }
           })
        .Columns(columns =>
        {
            columns.Bound(o => o.FileName).ClientTemplate("<ul class='t-menu'><li><a href='" + Url.Action("Download", "Document", new { entityId = "<#=EntityId#>" }) + "' class='t-link' ><div style='float:left'><img style='border: 0px' alt='NA' src='" + Url.Action("GetIcon", "Document", new { fileName = "<#=FileName#>" }) + "'/></div><#=FileName#></a></li></ul>").Width("40%").Title("Download");
            columns.Bound(o => o.Description);
            columns.Bound(o => o.Author);
            columns.Bound(o => o.DateTime).Format("{0:dd.MM.yyyy}");
            if (Roles.GetRolesForUser().Contains("Administrators") || Roles.GetRolesForUser().Contains("PowerUsers"))
            {
                columns.Bound(o => o.AuthenticationLevel);
                columns.Command(commands =>
                {
                    commands.Edit();
                    commands.Delete();
                }).Width(180).Title("");
            }
 
        })
        .DataBinding(dataBinding =>
        {
            dataBinding.Ajax().Enabled(true)
                .Select("_Index", "Document")
                .Update("_Update", "Document")
                .Delete("_Delete", "Document")
                .Insert("_Insert", "Document");
        })
        .DataKeys(dataKeys => dataKeys.Add(x => x.EntityId))
        .Editable(editable => editable.Mode(GridEditMode.PopUp))
        .Scrollable(scrolling => scrolling.Enabled(true).Height(500))
        .Sortable(sorting => sorting.Enabled(true))
        .Pageable(paging => paging.Enabled(true))
        .Filterable(filtering => filtering.Enabled(true))
                .ClientEvents(events => events.OnEdit("onEdit").OnSave("onSave"))
        .Footer(true)
%>


Hi, Michael because the reply function of this thread is not working i edit this post for you and hope you will read it.

Use

 $("#"+e.form.id).submit(function (e) {


instead of

$("#DocumentGridform").submit(function (e) {


this should work.


And here are my Methods:

[AcceptVerbs(HttpVerbs.Post)]
[GridAction]
public ActionResult _Index()
{
    return View(new GridModel(GetAll()));
}
 
[AcceptVerbs(HttpVerbs.Post)]
[GridAction]
public ActionResult _Update(Guid entityId)
{
    DocumentViewModel viewModel = Get(entityId);
 
    if (TryUpdateModel(viewModel))
    {
        Save(viewModel);
        HttpPostedFileBase file = Request.Files["File"];
        if (file != null && file.ContentLength != 0)
        {
            SaveDocument(viewModel.EntityId, file);
        }
    }
    return View(new GridModel(GetAll()));
}
 
[AcceptVerbs(HttpVerbs.Post)]
[GridAction]
public ActionResult _Insert()
{
    DocumentViewModel viewModel = new DocumentViewModel();
    if (TryUpdateModel(viewModel))
    {
         
            if (ModelState.IsValid)
            {
                Create(viewModel);
                HttpPostedFileBase file = Request.Files["File"];
                if (file != null && file.ContentLength != 0)
                {
                    SaveDocument(viewModel.EntityId, file);
                }
            }
    }
    return View(new GridModel(GetAll()));
}
 
[AcceptVerbs(HttpVerbs.Post)]
[GridAction]
public ActionResult _Delete(Guid id)
{
    DeleteDocument(id);
    return View(new GridModel(GetAll()));
}


0
James
Top achievements
Rank 1
answered on 18 Jan 2011, 09:19 PM
Manuel,

That worked perfectly, job well done.

Thanks

James
0
Michael
Top achievements
Rank 1
answered on 02 Mar 2011, 11:14 AM
Manuel,

I'm trying to get file upload functioanlity to work.  In your javascript functions, you call your grid "DocumentGrid".  What happens if my grid is named:

.Name(
"Files_<#= StudentID #>")

Because, I  am using the tab control,  I need to specify an identifier.   How would I name my grid in the javascript?

Also, do you mind posting the model methods, insert, update, delete, etc?

Thanks for any help.

Manuel, I got your reply in the post, thanks very much, I will check it out! 

Can you post your SaveDocument and DeleteDocument methods?  Also, how are you opening the file after its uploaded to view it?

Thanks, this really helps.
---------------------------------------------------------------------------------------------------------------------------------------------
Hi, Michael i have posted into your reply to keep at least the flow :) This forum isn't secure!

I don't have the code by the hand right now because it's on another PC so you have to wait till Monday. I should have posted all of it before :(

If you are in a hurry i can try to search equivalent code snippets for you.

---------------------------------------------------------------------------------------------------------------------------------------------

Hi Manuel, thanks for responding again.  Actually, I'm in a jam, and have to get this file functionality (upload & view) working as soon as I can (monday is actually the deadline).   You've given great examples so far.  If its not too much trouble, and additional guidance would be great, otherwise, I'll look for it Monday.

Thanks again...
---------------------------------------------------------------------------------------------------------------------------------------------

Hi, Micheal i found an old backup from november 2010 on my notebook from there i extracted some code snippets for you.

Save File
var file = Request.Files["File"];
if (file != null && file.ContentLength != 0)
{
byte[] data = new byte[file.ContentLength];
file.InputStream.Read(data, 0, file.ContentLength);
try
{
string directoryPath = ConfigurationManager.AppSettings["DocumentDirectory"];
if (!Directory.Exists(directoryPath))
{
Directory.CreateDirectory(directoryPath);
}
string filePath = Path.Combine(directoryPath, EntityID.ToString());
using (FileStream fileSteam = new FileStream(filePath, FileMode.Create, FileAccess.Write))
{
fileSteam.Write(data, 0, data.Length);
}
}
catch (Exception exc)
{
}
}

Delete File
   try
            {
                string directoryPath = ConfigurationManager.AppSettings["DocumentDirectory"];
                if (!Directory.Exists(directoryPath))
                {
                    Directory.CreateDirectory(directoryPath);
                }
                string filePath = Path.Combine(directoryPath, EntityID.ToString());
                System.IO.File.Delete(filePath);
            }
            catch (Exception exc)
            {
            }

Download

Column template for file download

columns.Bound(o => o.FileName).ClientTemplate("<ul class='t-menu'><li><a href='" + Url.Action("Download", "Document", new { entityId = "<#=EntityId#>" }) + "' class='t-link' ><div style='float:left'><img style='border: 0px' alt='NA' src='" + Url.Action("GetIcon", "Document", new { fileName = "<#=FileName#>" }) + "'/></div><#=FileName#></a></li></ul>").Width("40%").Title("Download");

Controller

 public ActionResult Download(Guid entityID)
        {
            DocumentViewModel documentViewModel = GetDocument(entityID);

                ControllerContext.HttpContext.Response.Buffer = true;
                ControllerContext.HttpContext.Response.Clear();
                ControllerContext.HttpContext.Response.AddHeader("content-disposition", "attachment; filename=" + documentViewModel.FileName);
                ControllerContext.HttpContext.Response.ContentType = documentViewModel.MimeType; //= "application/vnd.ms-excel";
                ControllerContext.HttpContext.Response.BinaryWrite(documentViewModel.GetData());
                ControllerContext.HttpContext.Response.End();
            }
            return RedirectToAction("LogOn", "Account");

        }
  public DocumentViewModel GetDocument(Guid entityID)
        {
            return ActiveRecordLinqBase<Document>.Queryable.Where(d=>d.EntityID.Equals(entityID))
                 .Select(d => new DocumentViewModel
                 {
                     EntityID = d.EntityID,
                     DateChanged = d.DateChanged,
                     DateCreated = d.DateCreated,
                     FileName = d.Name,
                     Author = d.Author,
                     Description = d.Description,
                     ChangedBy = d.ChangedBy,
                     CreatedBy = d.CreatedBy,
                     MimeType = d.MimeType,
                     AuthenticationLevel = d.AuthenticationLevel,
                 }).FirstOrDefault();

        }
 public byte[] GetData()
        {
            if (data == null)
                {
                    data = ReadByteArrayFromFile();
                    return data;
                }
                return data;
        }
public byte[] ReadByteArrayFromFile()
        {
            try
            {
                string directoryPath = ConfigurationManager.AppSettings["DocumentDirectory"];
                string filePath = Path.Combine(directoryPath, EntityID.ToString());
                byte[] data;
                using (FileStream fileSteam = new FileStream(filePath, FileMode.Open, FileAccess.Read))
                {
                    data = new byte[fileSteam.Length];
                    fileSteam.Read(data, 0, (int)fileSteam.Length);
                }
                return data;
            }
            catch (Exception exc)
            {
                return null;
            }
        }

I hope this helps, sry for being to lazy to format the code :)

-----------------------------------------------------------------------------------------------------------------------------------------------------------------

Manuel, thanks so much! I really appreciate your help and efforts! :)

UPDATE:

Manuel, I am getting object doesnt support this property or method of this line of the javascript OnEdit method:

$(

this

).ajaxSubmit(options);

Could it be the $("#" + e.form.id).submit(function(e) { is not properly defined?  My grid is in a detail view, on the second tab.

This is my view (if you search for "Files", that is where my file grid is).  I also have your object.asx defined.  As well as the UploadEditor.asx in the sample project above.

 

 

 

 

 

 

 

<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<GridAlphabeticPaging.Models.AlphabeticStudentsViewModel>" %>

 

<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
 Students
</asp:Content>

 

<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">

 

    <h2>Students</h2>

 

    <%Html.Telerik()
            .Grid<Models.Student>()
            .Name("Students")
            .DataKeys(k => k.Add(s => s.StudentID))
            .DataBinding(dataBinding => dataBinding
                .Ajax()
                    .Select("Select", "Student")
                    .Insert("Insert", "Student")
                    .Update("Update", "Student")
                    .Delete("Delete", "Student")
            )
             .ToolBar(toolBar => toolBar.Template(() =>
            {%>
                <a href="#" class="t-grid-action t-button t-state-default t-grid-add">Add Student</a>
                <div class="t-pager-wrapper" style="border-bottom:0">
                    <div class="t-pager t-reset">                               
                        <%foreach (var letter in Model.Letters)
                          {%>
                            <%=Html.ActionLink(letter, "Index", new { letter }, new { @class = "t-link" })%>
                        <%}%>
                        <%=Html.ActionLink("All", "Index")%>                                                       
                    </div>
                </div>
            <%}))
            .Columns(columns =>
            {
                columns.Bound(s => s.FirstName).Width(120).Filterable(true);
                columns.Bound(s => s.LastName).Width(120).Filterable(true);
                columns.Bound(s => s.School.SchoolName).Width(160).Filterable(true);
                columns.Command(commands =>
                {
                    commands.Edit();
                    commands.Delete();
                    //commands.Select();
                }).Width(150);
            })
            .DetailView(detailView => detailView.ClientTemplate(
                 Html.Telerik().TabStrip()
                .Name("TabStrip_<#= StudentID #>")
                .SelectedIndex(0)
                .Items(items =>
                {
                    items.Add().Text("Clinical Rotations").Content(
                          Html.Telerik().Grid<Models.StudentClinicalRotation>()
                           //Ensure the Name of each grid is unique
                          .Name("ClinicalRotations_<#= StudentID #>")
                          .DataKeys(keys =>
                          {
                              keys.Add(k => k.StudentClinicalRotationID);
                          })
                         .ToolBar(commands => commands.Insert())
                         .DataBinding(dataBinding => dataBinding.Ajax()
                             .Insert("InsertStudentClinicalRotation", "Student", new { id = "<#= StudentID #>" })
                             .Update("UpdateStudentClinicalRotation", "Student", new { id = "<#= StudentID #>" })
                             .Select("SelectStudentClinicalRotations", "Student", new { id = "<#= StudentID #>" })
                             .Delete("DeleteStudentClinicalRotation", "Student", new { id = "<#= StudentID #>" }))
                         .Columns(columns =>
                         {
                             columns.Bound(d => d.StartDate).Width(50).Format("{0:d}");
                             columns.Bound(d => d.EndDate).Width(50).Format("{0:d}");
                             columns.Bound(d => d.ClinicalRotation.ClinicalRotationName).Width(100).Title("Rotation");
                             columns.Bound(d => d.ClinicalRotationLocation.ClinicalRotationLocationName).Width(100).Title("Rotation Location");
                             columns.Command(commands =>
                             {
                                 commands.Edit();
                                 commands.Delete();
                             }).Width(125);
                         })
                         .DetailView(detailClinicalRotationView => detailClinicalRotationView.ClientTemplate(
                                    Html.Telerik().Grid<Models.StudentFee>()
                                    //Ensure the Name of each grid is unique
                                    .Name("Fees_<#= StudentClinicalRotationID #>")
                                    .DataKeys(keys =>
                                    {
                                        keys.Add(s => s.StudentFeeID);
                                    })
                                   .ToolBar(commands => commands.Insert())
                                   .DataBinding(dataBinding => dataBinding.Ajax()
                                       .Insert("InsertFee", "Student", new { id = "<#= StudentClinicalRotationID #>", studentID = "<#= StudentID #>" })
                                       .Update("UpdateFee", "Student", new { id = "<#= StudentClinicalRotationID #>" })
                                       .Select("SelectFees", "Student", new { id = "<#= StudentClinicalRotationID #>" })
                                       .Delete("DeleteFee", "Student", new { id = "<#= StudentClinicalRotationID #>" }))
                                   .Columns(columns =>
                                   {
                                       columns.Bound(s => s.PaidDate).Width(50).Format("{0:d}");
                                       columns.Bound(s => s.Amount).Width(50).Format("{0:c}"); ;
                                       columns.Command(commands =>
                                       {
                                           commands.Edit();
                                           commands.Delete();
                                       }).Width(250);
                                   })
                                   .Pageable()
                                   .Editable(editing => editing.Mode(GridEditMode.PopUp))
                                   .ToHtmlString()
                                   ))
                       .Pageable()
                       .Editable(editing => editing.Mode(GridEditMode.PopUp))
                       .ToHtmlString());
                    items.Add().Text("Files").Content(
                             Html.Telerik().Grid<Models.StudentFile>()
                                 .Name("Files_<#= StudentID #>")
                                 .ToolBar(commands => commands.Insert())
                                 .DataKeys(dataKey => dataKey.Add(f => f.StudentFileID))
                                 .ClientEvents(events => events.OnEdit("onEdit").OnSave("onSave"))
                                  .Columns(columns =>
                                 {
                                     columns.Bound(f => f.FileName).Width(100);
                                     columns.Bound(f => f.Data);
                                     columns.Command(command => command.Edit()).Width(100);
                                 })
                                 //.Editable(editing => editing.FormHtmlAttributes(new { enctype = "multipart/form-data" })
                                 //                            .Mode(GridEditMode.InForm))
                                 .Editable(editable => editable.Mode(GridEditMode.PopUp))
                                 .DataBinding(dataBinding => dataBinding.Ajax()
                                     .Insert("InsertFile", "Student", new { id = "<#= StudentID #>" })
                                     .Update("UpdateFile", "Student", new { id = "<#= StudentID #>" })
                                     .Select("SelectFile", "Student", new { id = "<#= StudentID #>" }))
                                 .ToHtmlString());
                })
                .ToHtmlString()
            ))
            .ClientEvents(events => events.OnLoad("onLoad"))
            .Filterable(filtarable => filtarable.Filters(filters =>
            {
                if (!string.IsNullOrEmpty(Model.SelectedLetter))
                {
                    filters.Add(s => s.LastName).StartsWith(Model.SelectedLetter);
                }
            }))
            .Scrollable(c => c.Height("400px"))
            .HtmlAttributes(new { @style = "width:100%" })
          //.Selectable()
            .Editable(editing => editing.Mode(GridEditMode.PopUp))
            .Render();
    %>
   
<script type="text/javascript">

 

    function onLoad(e) {
        var grid = $(this).data('tGrid');
        $(this).find("> .t-grid-toolbar a:not(.t-grid-add)").click(function(e) {
            e.preventDefault();
            var letter = $(this).text();
            if (letter == "All") {
                letter = "";
            }
            grid.rebind({ letter: letter });
        });
    }

 

    function onEdit(e) {
        var mode = e.mode;
        if (mode == 'insert') {
            $("#" + e.form.id).submit(function(e) {
                var options = { url: '/Student/InsertFile',
                    contentType: 'multipart/form-data',
                    type: 'POST',
                    success: function(result) {
                        $('div[class~="t-grid"]').data('tGrid').ajaxRequest();
                    }
                };
                $(this).ajaxSubmit(options);
                return false;
            });
        }

 

        if (mode == 'edit') {
              $("#" + e.form.id).submit(function(e) {
                var options = { url: '/Student/UpdateFile',
                    contentType: 'multipart/form-data',
                    type: 'POST',
                    success: function(result) {
                        $('div[class~="t-grid"]').data('tGrid').ajaxRequest();
                    }
                };
                $(this).ajaxSubmit(options);
                return false;
            });
        }
    };

 

    function onSave(e) {
        e.preventDefault();
        $("#" + e.form.id).submit();
        $("#" + e.form.id + 'PopUp').data('tWindow').center().close();
    };

 

</script>

 

</asp:Content>

 

 

ALSO: by the way, when I was trying to get this to work, I also tried to change popup to inform and inline, and commented out the .ClientEvents onEdit and OnSave that you provided.  I was able to successfully get to the control, but the request file was always null.   I am using last quarters release

------------------------------------------------------------------------------------------------------------------------------------------------------------Hi, Michael

Did you add the JQuery Form Plugin to your Javascript files and register it in your master page? Because this is necessary to use ajaxSubmit and submit your file via iFrame. 

 

------------------------------------------------------------------------

Manuel,  thanks again.  I didn't have that registered, i thought it was already included in the telerik scripts.  I put this on the master page, which now it seems to recognize the script.... but, I am now getting another error... see below:

<%

=

Html.Telerik().ScriptRegistrar().Scripts(scripts =>

 

 

 

 

 

 

scripts.AddGroup(

 

"CommonScript"

, group =>

 

 

 

 

 

 

group.Add(

 

"~/Scripts/jquery.form.js"

)

 

 

 

 

 

 

.Combined(

 

true

)

 

 

 

 

 

 

.Compress(

 

true

)

 

 

 

 

 

 

)

 

)

 

%>

 


On the line below:
$("#" + e.form.id + 'PopUp').data('tWindow').center().close();

I'm getting this error:
data(...) is null or not an object.

UPDATE:   I was able to overcome this error by setting the form name correctly (see below), but now, the popup window closes, but my controller code is not executed... if i try and keep going back and submitting the form the code is eventually executed, but the request file is null.  Can I test this locally, or do I need to post to a server to test uploading a file?

 

function

onSave(e) {

 

e.preventDefault();

 

 

 

 

 

var form_name = e.form.id.replace('form', 'PopUp'

);

 

$(

 

 

 

 

 

"#"

+ e.form.id).submit();

$(

 

 

 

 

"#" + form_name).data('tWindow'

).center().close();

};

 

 

 

 


UPDATE: I think I know what the problem is,  I need  to pass in "<#= StudentID #>" into the javascript OnEdit Student/UpdateFile call.  Not sure how to do that, but for testing purposes, I am hard coding that now.  I am getting the file permission denied.  I am on my local host (on my laptop), and I don't have a Users tab when I goto the file properties, so I can't set the ASPNET user account to have these permissions.  Is there another way I can set permissions? Also, in your example, how did you have your path defined below?

string directoryPath = ConfigurationManager.AppSettings["DocumentDirectory"];

I'm just trying to see it to:

string directoryPath = "/App_Data/StudentFiles";

-------------------------------------------------------------------------------------------------------------------------------------
Well i don't have a developer environment on my notebook right now so all i can do is giving you hints.

Can I test this locally, or do I need to post to a server to test uploading a file?  - You don't need a server it should work locally too.

I am on my local host (on my laptop), and I don't have a Users tab when I goto the file properties, so I can't set the ASPNET user account to have these permissions.  Is there another way I can set permissions? Also, in your example, how did you have your path defined below? - If Request files are empty then it's not a permission problem, if you can't write it to your hard disk then it is. Make sure you gave network service read/write permission on your upload folder. If your Request.Files is emty then it's a problem with your javascript code i guess. Make sure the request type in your controller action is multipart/form-data (You can check that by making a breakpoint und check via watch on Response.ContentType). So the first thing you should do is checking the content type.

I need  to pass in "<#= StudentID #>" into the javascript - passing values to javascript is hell as far as i know there are some way to do this but it's not so easy so this should be your last option.

UPDATE from Mike:

the file is {System.Web.HttpPostedFileWrapper} and my conent type is text.  I'm trying to uplaod a text file, so that looks good, right?

The code:

 

HttpPostedFileBase file = Request.Files["Data"];

 

 

 


and file has the correct content type and file name.

How about web.config settings?  Do I need <identity impersonate="true"/> in there?

-----------------------------

the response content type needs to be multipart/form-data. as far as i remember you have to check on response.contentype in your controller action
the directory path needs to be asolute
and i don't remember to set idenity impersonate so i don't think this is necessary.

plz post me your mail aadress this make things easier because injecting messages here is anoying :)
i have to go now so i will answer you tomorrow again, you should debug your javascript code und test if axajsubmit is working correctly. and as long as you controller action is not executed then something with your javascript code is wrong.

if you not succeed this we i can send you a small test project on monday.


-------------------------------------------

My email address is michael1174@comcast.net

I haven't gotten it to work yet, but I'm still debugging... looking forward to hearing back from you.  Thanks for all your help...

Tags
General Discussions
Asked by
Manuel
Top achievements
Rank 1
Answers by
Rosen
Telerik team
Manuel
Top achievements
Rank 1
Aaron
Top achievements
Rank 1
James
Top achievements
Rank 1
Michael
Top achievements
Rank 1
Share this question
or