FileUpload control in ASP.NET MVC2 C# - asp.net

enter code hereI am trying to upload a file using FileUpload Control. As there are so many complexities within my form, I cannot use Html.BeginForm (of course this works perfectly fine). All I want to do is with Input id call the function to send the postedfile to the controller. I searched in the web, but my need is this. I DO NOT WANT TO SUBMIT THE WHOLE FORM. All I want to do is upload file and comeback to my form to complete the rest of the fields. Any type of code snippet would be appreciated. Thanks
Here is the sample of code what I have
<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
ViewReportFiles
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<% using (Html.BeginForm([ActionName], [ControllerName], FormMethod.Post, new { target = "_blank" }))
{%>
Here I have few fields to process.
Along with this I have fileUpload control
<table>
<tr>
<td valign="bottom">
<input type="file" id="document" name="document" accept="text/xml, text/csv, application/vnd.ms-excel, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" size="76" />
</td>
<td valign="bottom">
<div Id="UploadFile"> <input type="image" alt="upload file" src="<%= ResolveUrl("~/media/form_upload_btn.png") %>" name="image" /> </div>
</td>
</tr>
</table>
<% }>
My javascript is as follows
<script type="text/javascript" language="javascript">
$("#UploadFile").click(function () {
if ($("#document").val() == '') {
// checking for selected file
alert('Please select a document.');
return false;
}
$.ajaxFileUpload({
**url: '<%= Url.Action("actionName", "Controller") %>',**
data: { val: 'aaa' },
secureuri: false,
fileElementId: 'document',
dataType: 'xml',
success: function (data) {
}
});
});
</script>
Here the problem is it's not getting into that URL. it goes to my HTTPPost of the page.
My controller code is like this....
public void UploadAccessDataFile(){
foreach (string uploadFile in Request.Files)
{
}
}
Please help.

I am trying to upload a file using FileUpload Control
Don't try this to do this. Read the following blog post which explains how to upload files in an ASP.NET MVC application.

Related

How to open an aspx page like a dialog in ASP.NET

I need to open a page like a modal dialog .I find an exemple on net but it doesn't work.
In the main page I have this code:
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
<asp:Button Text ="Add New Course" runat="server" ID="btnAddCourse" OnClientClick="showPanel('dialog');return false;"/>
<script type="text/javascript">
function showPanel(panelID) {
$panel = $('#' + panelID);
$.ajax({
url: "/AddNew.aspx",
type: "GET",
dataType: "html",
async: false,
data: { "param": "abcd"
},
success: function (obj) {
// obj will contain the complete contents of the page requested
// use jquery to extract just the html inside the body tag
$content = $(obj).find('body').html();
// then update the dialog contents with this and show it
$panel.html($content);
$panel.dialog();
}
});
}
</script>
<div id="dialog">
</div>
</asp:Content>
When I click the button I need to open the page below .I receive an error that tell that element $ is not recognized.I don't know exactly who is element panel .Must I add a panel control ,but where ?
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="AddNew.aspx.cs" Inherits="WebApplicationDialog.AddNew" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Add New Course </title>
</head>
<body>
<form >
<div id="div1">
<table>
<tr><td colspan="3"> <asp:Label ID="lblCourse" runat="server" Text="Add New Course"></asp:Label></td></tr>
<tr><td colspan="3"> </td></tr>
<tr>
<td style="width:40%"> <asp:Label ID="lblName" runat="server" Text="Course Name" ></asp:Label></td>
<td style="width:20%"> </td>
<td style="width:40%">
<input id="txtName" type="text" />
</td>
</tr>
<tr>
<td style="width:40%"> <asp:Label ID="lblDescription" runat="server" Text="Description" ></asp:Label></td>
<td style="width:20%"> </td>
<td style="width:40%">
<input id="txtDescription" type="text" />
</td>
</tr>
<tr><td colspan="3" style="float:right">
<input value ="Save" id="btnSave" type="submit" /> </td></tr>
</table>
</div>
</form>
</body>
</html>
Can somebody help me with this code ,to make it works ?
Thanks
It looks like you are trying to use JQuery to load a page content into a panel but if I'm reading your code right you may not have included the JQuery library, you need to include this line of code in the <head> of your html code. You are also using JQueryUI dialog and will need to reference the JQueryUI library
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.9.1/jquery-ui.min.js"></script>
For Example
<head>
<title>Page Title</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.9.1/jquery-ui.min.js"></script>
<head>
EDIT: I also notice you are using the dialog, which is in JQuery UI, pleasse make sure you reference JQuery UI toolkit as well
EDIT: Have stripped your code into jsFiddle: http://jsfiddle.net/EhPk7/1/
this seems to work for me
You need to add jquery lib reference.
At the top of a page:
<script src="http://code.jquery.com/jquery-1.8.2.min.js"/>
Include jQuery.
Change this line -> $panel = $('#' + panelID); to -> $panel = $('#div1'); and see if it works.
Consider adding jQuery script references on your page, above the jQuery Code that you are using.
Also, add reference jQuery UI
Download jQuery
There is a boolean property/setting called modal on the jQueryUI dialog, this will create a modal-type dialog.
I myself use this:
d.dialog({
autoOpen: true,
closeOnEscape: false,
closeText: '',
modal: true,
draggable: false,
resizable: false,
width: (window.document.width * 0.75),
dialogClass: 'popup loading',
title: 'title'),
});
when you wrap this sort of function in the
$(document).ready(function() {
})
it should popup the moment the DOM is ready..

ASP.NET Server does not process pages asynchronously

I have a page with button, and i want to load 2 data grids with data asynchronously by cliking the button.
This is the code of the page, I use jquery to make calls to other 2 pages that will yield me html.
<%# Page Title="" Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true" CodeFile="Test.aspx.cs" Inherits="Solutions_CashCenter_StockManagement_Test_Test" %>
<asp:Content ID="Content2" ContentPlaceHolderID="cphCenter" Runat="Server">
<style type="text/css">
#wait {
position:absolute;
top:0px;
right:10px;
width:200px;
z-index:1000;
vertical-align:middle;
text-align:center;
background: #febf00;
display:none;
}
</style>
<script src='<%= ResolveUrl("../../../../Scripts/jquery-1.4.1.js") %>' type="text/javascript"></script>
<script type="text/javascript">
$(function () {
$('#wait')
.ajaxStart(function () { $(this).show(); })
.ajaxStop(function () { $(this).hide(); });
$('input:button').live('click', loadData);
});
function loadData() {
$.get("Source.aspx", {},
function (data) {
$('#a1').html(data);
},
"html");
alert('This alert is asynchronous (1st)');
$.get("Source2.aspx", {},
function (data) {
$('#a2').html(data);
},
"html");
alert('This alert is asynchronous (2nd)');
}
</script>
<div id="test13">
<input type="button" id="btnLoad" value="Load" />
</div>
<div id="a1"></div>
<div id="a2"></div>
<div id="wait">Please wait <img src="ajax-loading.gif" /></div>
</asp:Content>
Then I have 2 aspx pages, Source1.aspx and Source2.aspx. They only containe a gridDataView and little code in OnLoad event.
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Source.aspx.cs" Inherits="Solutions_CashCenter_StockManagement_Test_Source" %>
<form runat="server">
<cc1:GridDataView runat="server" ID="gridTest" >
</cc1:GridDataView>
<asp:SqlDataSource ID="dsTest" runat="server" ConnectionString="<%$ ConnectionStrings:WebPortalConnectionString %>"
ProviderName="<%$ ConnectionStrings:WebPortalConnectionString.ProviderName %>">
</asp:SqlDataSource>
</form>
Server-side:
Thread.Sleep(5000);
dsTest.SelectCommand = "SELECT 'test1', 'test2', 'test3'";
this.gridTest.DataSourceID = "dsTest";
this.gridTest.DataBind();
And the same for the second page, but with different data for the grid.
What I have in result is that both alerts happen at once, but the grids are loaded one after one, that is 1st grid appears after 5 seconds, and then second one appers after another 5 sec.
That is the server does not actually process them concurrently.
What am I doing wrong and how should I organize all to work as I need?
This is happens because the session locks the page reads.
So when the one page is loading, the session lock all the rest request until is finish and send the page.
To make it work you need ether to disabled the session on this pages, ether use handler that is not have by default session lock.
Relative questions :
Trying to make Web Method Asynchronous
Web app blocked while processing another web app on sharing same session
What perfmon counters are useful for identifying ASP.NET bottlenecks?
Replacing ASP.Net's session entirely

ASP.NET MVC2 Application's submit button returns URL with an appended "Form"

OK, I'm sorry if the tile of the question was unclear, and if you understand what I mean, please don't hesitate to help me think of a better one.
Anyway, I have a <input type="submit"> element for my form, and I want it to return the same URL as the URL of the page the element is on.
Currently, if I click the button, it takes me from /Calculate/Quadratic to /Calculate/QuadraticForm
In my controller for this view, I have the following code:
[AcceptVerbs(HttpVerbs.Get)]
public ViewResult Quadratic()
{
ViewData["Root1"] = "";
ViewData["Root2"] = "";
return View();
}
[AcceptVerbs(HttpVerbs.Post)]
public ViewResult Quadratic(QuadCalc boss)
{
ViewData["Root1"] = x1;
ViewData["Root2"] = x2;
return View();
}
And here is the markup and code for my Quadratic view page, which includes the form which includes the submit button I've been referring to:
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<h2>Quadratic</h2>
<% using(Html.BeginForm("QuadraticForm", "Calculate")) %>
<% { %>
<div>
a: <%= Html.TextBox("quadraticAValue") %>
<br />
b: <%= Html.TextBox("quadraticBValue") %>
<br />
c: <%= Html.TextBox("quadraticCValue") %>
<br />
<input type="submit" id="quadraticSubmitButton" value="Calculate!" />
<br />
<p><%= ViewData["Root1"] %></p>
<p><%= ViewData["Root2"] %></p>
</div>
<% } %>
</asp:Content>
Therefore, all I really want is to have the submit button return the same page, but the HTTP post will aid the application in passing new ViewData. Unless I'm interpreting this all wrong.
The problem is in your BeginForm method that calls the QuadraticForm action
<% using(Html.BeginForm("QuadraticForm", "Calculate")) %>
If you want to give an ID to the form you should use
<% using (Html.BeginForm("Quadratic", "Calculate", FormMethod.Post, new { id = "QuadraticForm" })) { %>
If you dont mind about the ID and want to just return to the same action just use
<% using(Html.BeginForm() %>
The parameters are:
The action name
The controller Name
The form method (get/post)
The form attributes

MVC Ajax not loading Partial View in div, loading new page

I'm currently working with MVC 1.0 and have never worked with AJAX before and only have limited experience (started a little more than a week ago) with ASP.Net MVC. I'm trying to setup a table (that's built / is in a partial view) that's populated with information from a db that allows a user to quickly add pr remove records into or from the db right from the table. I'm trying to use AJAX to get this done because there is a lot of other information on the rest of the page that I don't want to have to reload. Here's a quick template.
row1: (text box) Add
row2: Name1 Remove
row3: Name2 Remove
So when a user wants to, they can enter a name into the (text box) hit Add and an action in the controller will add the entered name into the database and reload the partial view with the most up to date information.
So far I have been able to get the action method to be called, and add the record into the database. The problem is that it does not reload JUST the partial-view. It instead loads the partial-view as a whole new page and it's content is the only one that displays. (Instead of staying at /Project/Details/5, the page loads /Project/MembersDisplay)
In my master page I have:
<script src="<%= Links.Scripts.jquery_1_3_2_min_js %>" type="text/javascript"></script>
<script src="<%= Links.Scripts.MicrosoftAjax_js %>" type="text/javascript"></script>
<script src="<%= Links.Scripts.MicrosoftMvcAjax_js %>" type="text/javascript"></script>
In the controller I have:
[AcceptVerbs(HttpVerbs.Post)]
public virtual ActionResult AddMember(FormCollection form)
{
MemberRepository repo = new MemberRepository();
Member m = new Member();
m.Id = Convert.ToInt32(form["Id"]);
m.Name = form["name"];
try{
repo.addMember(m);
repo.save();
}
catch{
return View();
}
// Make a new IList of All Members in this current
//IList<Member> mems = (new PRDataContext()).Members_GetMembersById(m.Id).ToList<Member>();
return View("MembersDisplay", members);
}
The Partial view is
<%# Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<List<Application.Models.Member>>" %>
<script src="/Scripts/MicrosoftAjax.js" type="text/javascript"></script>
<script src="/Scripts/MicrosoffMvcAjax.js" type="text/javascript"></script>
<table>
<% if (Model.Count() > 0) { %>
<% foreach (var p in ViewData.Model) { %>
<tr>
<td><%= Html.Encode(p.Name) %></td>
<td><%= Ajax.ActionLink("Delete", "AjaxDelete", new { p.Id, p.Name }, new AjaxOptions { Confirm = "Delete?", HttpMethod = "AjaxDelete", UpdateTargetId = "results" })%></td>
</tr>
<% } %>
<% } else { %>
<tr>
<td><b>There are no Members.</b></td>
</tr>
<% } %>
</table>
In the controller, I tried adding if(Request.IsAjaxRequest()==true) the branch never executed. I'm not sure if ajax isn't loading, or what I'm doing wrong.
EDIT - Added missing code
Here's the details portion that uses the partial view:
<table>
<% Ajax.BeginForm("AddMember", "Project", new AjaxOptions { UpdateTargetId = "results", InsertionMode=InsertionMode.Replace}) { %>
<tr>
<td align="left" colspan="2" style="background-color:#93B6E0;"><font style="color:#fff;"><b>Members</b></font></td>
</tr>
<tr>
<td width="80%">
<input type="hidden" name="prjId" value="<%= Html.Encode(Model.Id) %>" /><input type="text" name="name" style="width:120px;" />
</td>
<td width="20%">
<input type="submit" value="Add" />
</td>
</tr>
<% } %>
<tr>
<td colspan="2">
<div id="results"><% Html.RenderPartial(MVC.Members.Views.MembersDisplay, Model.Members.ToList<Member>()); %></div>
</td>
</tr>
Dirk - not sure if the complete code is there. however, from a brief glance, your returning:
return View("MembersDisplay", members);
when in fact, for a partial view, you should be returning something like:
return PartialView("MembersDisplay", members);
hope this helps
jim
If you're intending the submit to fire the Ajax.BeginForm, you'll need to include it in the form with curly braces. Currently your submit is not within the form.
I upgraded to MVC 2.0 as #RailRhoad suggested.
Then I moved the partial view to an area and has to change the path links to the .js files to be more explicit (T4MVC wasn't rendering the correct paths). Instead of
<script src="/Scripts/MicrosoftAjax.js" type="text/javascript"></script>
or
<script src="<%= Links.Scripts.MicrosoftAjax_js %>" type="text/javascript"></script>
I had to do
<script src="../../../../Scripts/MicrosoftAjax.js" type="text/javascript"></script>
Also, the action in the controller worked as #jim suggested by
return PartialView(MVC.ProjectDash.Project.Views.MembersDisplay, members);
Also, I removed the "InsertionMode=..." from
<% Ajax.BeginForm("AddMember", "Project", new AjaxOptions { UpdateTargetId = "results", InsertionMode=InsertionMode.Replace}) { %>
The biggest issue was the javascript files were not be linked up and referenced correctly. Once that was fixed, the other things quickly feel into place.

ASP.NET MVC 2 - Saving child entities on form submit

I'm using ASP.NET MVC 2 and am struggling with saving child entities. I have an existing Invoice entity (which I create on a separate form) and then I have a LogHours view that I'd like to use to save InvoiceLog's, which are child entities of Invoice. Here's the view:
<%# Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<TothSolutions.Data.Invoice>" %>
<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
Log Hours
</asp:Content>
<asp:Content ID="Content3" ContentPlaceHolderID="HeadContent" runat="server">
<script type="text/javascript">
$(document).ready(function () {
$("#InvoiceLogs_0__Description").focus();
});
</script>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<h2>Log Hours</h2>
<% using (Html.BeginForm("SaveHours", "Invoices")) {%>
<%: Html.ValidationSummary(true) %>
<fieldset>
<legend>Fields</legend>
<table>
<tr>
<th>Date</th>
<th>Description</th>
<th>Hours</th>
</tr>
<%
int index = 0;
foreach (var log in Model.InvoiceLogs) {
%>
<tr>
<td><%: log.LogDate.ToShortDateString() %></td>
<td><%: Html.TextBox("InvoiceLogs[" + index + "].Description")%></td>
<td><%: Html.TextBox("InvoiceLogs[" + index + "].Hours")%></td>
<td>Hours</td>
</tr>
<%
index++;
}
%>
</table>
<p>
<%: Html.Hidden("InvoiceID") %>
<%: Html.Hidden("CreateDate") %>
<input type="submit" value="Save" />
</p>
</fieldset>
<% } %>
<div>
<%: Html.ActionLink("Back to List", "Index") %>
</div>
</asp:Content>
And here's the controller code:
//GET: /Secure/Invoices/LogHours/
public ActionResult LogHours(int id)
{
var invoice = DataContext.InvoiceData.Get(id);
if (invoice == null)
{
throw new Exception("Invoice not found with id: " + id);
}
return View(invoice);
}
//POST: /Secure/Invoices/SaveHours/
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult SaveHours([Bind(Exclude = "InvoiceLogs")]Invoice invoice)
{
TryUpdateModel(invoice.InvoiceLogs, "InvoiceLogs");
invoice.UpdateDate = DateTime.Now;
invoice.DeveloperID = DeveloperID;
//attaching existing invoice.
DataContext.InvoiceData.Attach(invoice);
//save changes.
DataContext.SaveChanges();
//redirect to invoice list.
return RedirectToAction("Index");
}
And the data access code:
public static void Attach(Invoice invoice)
{
var i = new Invoice { InvoiceID = invoice.InvoiceID };
db.Invoices.Attach(i);
db.Invoices.ApplyCurrentValues(invoice);
}
In the SaveHours action, it properly sets the values of the InvoiceLog entities after I call TryUpdateModel but when it does SaveChanges it doesn't update the database with the new values. Also, if you manually update the values of the InvoiceLog entries in the database and then go to this page it doesn't populate the textboxes so it's clearly not binding correctly.
Thanks,
Justin
Got it working, I needed to populate the InvoiceLogID and InvoiceID in hidden fields so they'd get populated in the EntityCollection.

Resources