asp.net mvc + Ajax.BeginForm OnBegin not firing - ajax

After reading several posts regarding this issue, it is mostly related to including
<script src="~/Scripts/jquery.unobtrusive-ajax.js"></script>
and the proper order of including jquery first.
<script src="~/Scripts/jquery-1.12.4.js"></script>
I think I did properly, but OnBegin is not firing still.
_Layout.cshtml:
<head>
<meta charset="utf-8" />
<meta content='width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0' name='viewport' />
<title>Test</title>
#Scripts.Render("~/bundles/modernizr")
<script src="~/Scripts/jquery-1.12.4.js"></script>
<script src="~/Scripts/bootstrap.min.js"></script>
<script src="~/Scripts/respond.min.js"></script>
<script src="~/Scripts/jquery.dataTables.js"></script>
<script src="https://cdn.datatables.net/responsive/2.1.0/js/dataTables.responsive.min.js"></script>
<script src="https://cdn.datatables.net/buttons/1.2.2/js/dataTables.buttons.min.js"></script>
<script src="https://cdn.datatables.net/buttons/1.2.2/js/buttons.colVis.min.js"></script>
<script src="~/Scripts/light-bootstrap-dashboard.js"></script>
<script src="~/Scripts/bootstrap-notify.js"></script>
<script src="~/Scripts/jquery.unobtrusive-ajax.js"></script>
<script src="~/Scripts/jquery.validate.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.js"></script>
#RenderSection("scripts", required: false)
</head>
So the order of process is:
School View:
#model Test.Models.School
<div class="editorRow">
#using (Html.BeginCollectionItem("schools"))
{
#Html.ActionLink("New Employee", "NewEmployee", "Test", new
{
#class = "btn btn-info btn-md",
data_toggle = "modal",
data_target = "#modal-container-employee"
})
</div>
<div id="modal-container-employee" class="modal fade" tableindex="-1" role="dialog">
<div class="modal-content">
<div class="modal-body">
</div>
</div>
</div>
Controller:
public ActionResult NewEmployee()
{
var newEmployee = new Employee();
return View(newEmployee);
}
Employee view:
#model Test.Models.Employee
#{
Layout = null;
}
#using (Ajax.BeginForm("PostEmployee", "Employee", new AjaxOptions
{
HttpMethod = "post",
InsertionMode = InsertionMode.Replace,
OnBegin = "closeModal"
}))
{
#Html.AntiForgeryToken()
<div id="test" class="">
<div class="modal-title title">
<input type="submit" id="submit" value="Save" /><span id="closes">x</span>
</div>
#Html.EditorFor(model => model.FullName)
</div>
}
<script>
function closeModal() {
$('#modal-container').modal('hide');
}
</script>
controller:
[HttpPost]
public ActionResult PostEmployee(Employee model)
{
try
{
var newEmployee = new Employee
{
FullName = model.FullName
};
db.Employees.Add(newEmployee);
db.SaveChanges();
return Json(new { status = "success" }, JsonRequestBehavior.AllowGet);
}
catch (Exception ex)
{
return Json(new { status = "error", errorMessage = ex.Message }, JsonRequestBehavior.AllowGet);
}
}
As a result, "success" Json is returned, but ajax is not catching it, it directly goes to the other page where it shows JSON array {"status":"success"}.
Can anyone find the problem?

Related

does not contain public definition for get enumerator

my view statement shows error that " for each statement cannot operate on variables of type public definition for 'get enumerator' "
I defined all objects in model and view models. still i get this error. any solution for this?
MY VIEW:
#using Edi.ViewModel
#model viewmodel
#{
<link rel="stylesheet" type="text/css" href="~/Content/style.css" />
Layout = null;
}
<!DOCTYPE html>
<html lang="en">
<head>
<link href="~/Content/Site.css" rel="stylesheet" />
<link href="~/Content/bootstrap.min.css" rel="stylesheet" />
<link href="~/Content/bootstrap.css" rel="stylesheet" />
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
</head>
<body>
<form id="form1" name="zoo">
<div class="med">
<pre>
<fieldset id="field1">
<legend>Bill Date Range</legend>
<input type="checkbox">After <input type="date" /> <input type="checkbox">Before <input type="date" />
</fieldset>
<fieldset id="field2">
<legend>Options</legend>
<label>Facility</label> #Html.DropDownListFor(Model => Model.Facility, Model.Facility, "Select Facility", new { style = "width:200px; height :30px" })
<label>Ins Queue</label> #Html.DropDownListFor(Model => Model.InsQueue, Model.InsQueue, "Select InsQueue", new { style = "width:200px; height:30px" })
Claim type <select style="width: 100px; height:30px"><option value="ALL">All</option><option value="NEW">New</option><option value="RESUBMIT">Resubmit</option></select>
</fieldset>
<pre>
<label>No of Bills Selected </label><input type="text" size="1" /> <label> EDI send To </label> #Html.DropDownListFor(Model => Model.EdiSendTo, Model.EdiSendTo, "Select Edi", new { style = "width:200px; height :30px" }) <button type="button" onclick="">Select All</button> <button type="reset" onclick="">Refresh</button> <button type="button" onclick="">Clear All</button> <button type="button" onclick="">Edit Bill</button>
</pre>
<table id="myTable">
<tr class="hd">
<th>visit</th>
<th>billno</th>
<th>patient</th>
<th>providername</th>
<th>insname</th>
<th>payby</th>
<th>inscode</th>
<th>user</th>
<th>claimtype</th>
</tr>
-------------------#foreach (var items in Model)------------------------------
{
<tr onclick="javascript:showRow1(this);">
<td>#items.visit</td>
<td>#items.billno</td>
<td>#items.Patient</td>
<td>#items.ProviderName</td>
<td>#items.InsName</td>
<td>#items.PayBy</td>
<td>#items.InsCode</td>
<td>#items.User</td>
<td>#items.ClaimType</td>
</tr>
}
</table>
</div>
</form>
</body>
</html>
MY CONTROLLER:
namespace Edi.Controllers
{
public class HomeController :Controller
{
// GET: Home
public ActionResult Index()
{
mbill mt = new mbill();
billing db = new billing();
viewmodel vm = new viewmodel();
vm.Facility = db.Add1();
vm.EdiSendTo = db.Add2();
vm.InsQueue = db.Add3();
List<mbill> itemlist = new List<mbill>();
itemlist = db.Index();
return View("Index",vm);
}
}
}
MY MODEL:
public List<mbill> Index()
{
List<mbill> itemList = new List<mbill>();
connection();
SqlCommand cmd = new SqlCommand("procGetEDIBills", con);
cmd.CommandType = CommandType.StoredProcedure;
con.Open();
SqlDataAdapter sd = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
sd.Fill(dt);
mbill item = new mbill();
using (SqlDataReader sdr = cmd.ExecuteReader())
{
mbill io = new mbill();
while (sdr.Read())
{
io = new mbill();
io.visit = sdr["VisitDate"].ToString();
io.billno = sdr["Billno"].ToString();
io.Patient = sdr["PatientName"].ToString();
io.ProviderName = sdr["ProviderName"].ToString();
io.InsName = sdr["InsuranceName"].ToString();
io.PayBy = sdr["BillPayBy"].ToString();
io.InsCode = sdr["InsuranceId"].ToString();
io.User = sdr["QueueByUser"].ToString();
io.ClaimType = sdr["ClaimType"].ToString();
itemList.Add(io);
}
}
con.Close();
return itemList;
}
}
if i delete #using Edi.ViewModel, #model viewmodel, on view then foreach error disappears and dropdownlistfor shows does not contain definition for dropdownlistfor error.

ValidateAntiForgeryToken throwing error

My controller is throwing the error
The required anti-forgery form field "__RequestVerificationToken" is not present.
But This is exactly what I am doing
Logging in with test user
VIEW
#using (Html.BeginForm(new { ReturnUrl = ViewBag.ReturnUrl }))
{
#Html.AntiForgeryToken()
#Html.ValidationSummary()
<fieldset>
<legend>Log in Form</legend>
<ol>
<li>
#Html.LabelFor(m => m.UserName)
#Html.TextBoxFor(m => m.UserName)
</li>
<li>
#Html.LabelFor(m => m.Password)
#Html.PasswordFor(m => m.Password)
</li>
<li>
#Html.LabelFor(m => m.RememberMe)
#Html.CheckBoxFor(m => m.RememberMe)
</li>
CONTROLLER
[AllowAnonymous]
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Login(LoginModel model, string returnUrl)
{
if (ModelState.IsValid)
{
if (Membership.ValidateUser(model.UserName, model.Password))
{
FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);
return RedirectToCreateUserProfile(model, returnUrl);
}
else
{
ModelState.AddModelError("", "The user name or password provided is incorrect.");
}
once authenticated i am redirected to the home page
then i click on a menu option to show me user profile and i get the above error
LAYOUT VIEW (Showing more code the needed but want to make the JS is causing an issue)
<!DOCTYPE html>
<html>
<head>
<title>#ViewBag.Title</title>
<link href="#Url.Content("~/Content/Site.css")" rel="stylesheet" type="text/css" />
<link href="#Url.Content("~/Content/kendo/2013.2.918/kendo.common.min.css")" rel="stylesheet" type="text/css" />
<link href="#Url.Content("~/Content/kendo/2013.2.918/kendo.dataviz.min.css")" rel="stylesheet" type="text/css" />
<link href="#Url.Content("~/Content/kendo/2013.2.918/kendo.metro.min.css")" rel="stylesheet" type="text/css" />
<link href="#Url.Content("~/Content/kendo/2013.2.918/kendo.dataviz.metro.min.css")" rel="stylesheet" type="text/css" />
<script src="#Url.Content("~/Scripts/kendo/2013.2.918/jquery.min.js")"></script>
<script src="#Url.Content("~/Scripts/kendo/2013.2.918/kendo.all.min.js")"></script>
<script src="#Url.Content("~/Scripts/kendo/2013.2.918/kendo.aspnetmvc.min.js")"></script>
<script src="#Url.Content("~/Scripts/kendo.modernizr.custom.js")"></script>
<script type="text/javascript">
var _gaq = _gaq || [];
var pluginUrl =
'//www.google-analytics.com/plugins/ga/inpage_linkid.js';
_gaq.push(['_require', 'inpage_linkid', pluginUrl]);
_gaq.push(['_setAccount', 'UA-44529127-1']);
_gaq.push(['_trackPageview']);
(function () {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
</head>
<body>
<header>
<div class="content-wrapper">
<div class="float-left">
<p class="site-title">#Html.ActionLink("your logo here", "Index", "Home")</p>
</div>
<div class="float-right">
<section id="login">
#Html.Partial("_LoginPartial")
</section>
<nav>
<ul id="menu">
<li>#Html.ActionLink("Home", "Index", "Home")</li>
<li>#Html.ActionLink("About", "About", "Home")</li>
<li>#Html.ActionLink("Contact", "Contact", "Home")</li>
#if (User.IsInRole("Admin"))
{
<li>#Html.ActionLink("API", "Index", "Help", new { area = "" }, null)</li>
}
</ul>
</nav>
</div>
</div>
</header>
<div id="body">
#if (Request.IsAuthenticated)
{
<ul id="IndexHomeMenu">
#if (User.IsInRole("Admin"))
{
<li>
Administration#*#Html.ActionLink("Administration", "Contact", "Home")*#
<ul>
<li>#Html.ActionLink("Manage Roles", "Index", "AdminView")</li>
<li>#Html.ActionLink("Manage Users", "Contact", "Home")</li>
<li>#Html.ActionLink("Inactive Reasons", "Index", "InactiveReasonView")</li>
</ul>
</li>
}
<li>
My Information
<ul>
<li>#Html.ActionLink("Profile", "EditByName", "UserView", new { UserName = User.Identity.Name }, new { #class = "selected" })</li>
<li>#Html.ActionLink("Phone Numbers", "Active", "PhoneNumberView",new {userName= User.Identity.Name },null)</li>
<li>#Html.ActionLink("Address's", "Active", "AddressView",new {userName= User.Identity.Name },null)</li>
#if(!User.IsInRole("Clients")){
<li>#Html.ActionLink("Subscription", "Index", "AdminView")</li>}
</ul>
I am clicking on #Html.ActionLink("Profile", "EditByName", "UserView", new { UserName = User.Identity.Name }, new { #class = "selected" })
CONTROLLER
[ValidateAntiForgeryToken]
public ActionResult EditByName(string userName)//EditByName
{
if (User.Identity.IsAuthenticated)
{
UserModel usermodel = repository.Get(User.Identity.Name);// db.UserModels.Find(id);
if (usermodel == null)
{
return RedirectToAction("Create","UserView", User.Identity.Name);
}
return View(usermodel);
}
else { return RedirectToAction("Login", controllerName: "AccountView"); }
}
This is when the error occurs. and im not sure whats missing, I am creating the token and it is on all forms.
You are using the [ValidateAntiForgeryToken] on a GET action (The EditByName action), while it is meant to work on POST actions.
See this question on the [ValidateAntiForgeryToken] purpose and this article explaining how to prevent CSRF attacks using it.
Remove the [ValidateAntiForgeryToken] from the EditByName GET-action method.
Also, use the [Authorize] atrribute instead of if (User.Identity.IsAuthenticated).
And may any user edit any profile, as long as they know the username?

ajax. The resource cannot be found

I'm using C# asp.net mvc4 and trying to do ajax search. But ther is error and it says " The resource cannot be found.".
What I'm doing wrong?
Controller
//Search
[HttpPost]
public ActionResult ContractSearch(string Name)
{
var contracts = db.Contracts.Include(c => c.DocType).Include(c => c.CreditType).Include(c => c.Bank).Include(c => c.UserProfile).Where(c => c.FirstName.Equals(Name));
return View(contracts.ToList());
}
View
#model IEnumerable<CreditoriyaApp.Models.Contract>
#{
ViewBag.Title = "Index";
}
<div>
#using (Ajax.BeginForm("ContractSearch", "Contract", new AjaxOptions { UpdateTargetId = "searchresults" }))
{
<input type="text" name="Name" />
<input type="submit" value="Search" />
}
<div id="searchresults">
#if (Model != null && Model.Count()>0)
{
<ul>
#foreach (var item in Model)
{
<li>#item.FirstName</li>
}
</ul>
}
</div>
Error
Server Error in '/' Application.
The resource cannot be found.
Description: HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable. Please review the following URL and make sure that it is spelled correctly.
Requested URL: /Contract/ContractSearch
Add the below in your controller. Then your error will be corrected.
public ActionResult ContractSearch()
{
return View();
}
for searching you can try something like below example.
Model:
public class Person
{
public string Name { get; set; }
public string Country { get; set; }
}
Controller:
public ActionResult SearchPerson()
{
return View();
}
[HttpPost]
public ActionResult SearchPerson(string searchString)
{
System.Collections.Generic.List<Person> lst = new List<Person>();
lst.Add(new Person { Name = "chamara", Country = "Sri Lanka" });
lst.Add(new Person { Name = "Arun", Country = "India" });
if (!string.IsNullOrEmpty(searchString))
{
lst = lst.AsEnumerable().Where(r => r.Name.Contains(searchString)).ToList();
}
string result = string.Empty;
result = "<p>Search Result<p>";
foreach (Person item in lst)
{
result = result + "<p> Names is: " + item.Name + " and Country is:" + item.Country + "<p>";
}
return Content(result, "text/html");
}
View:
#model IEnumerable<Mvc4Test.Models.Person>
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>SearchPerson</title>
<script src="#Url.Content("~/Scripts/jquery-1.7.1.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.unobtrusive-ajax.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.validate.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.validate.unobtrusive.js")" type="text/javascript"></script>
</head>
<body>
#using (Ajax.BeginForm("SearchPerson", "Search", new AjaxOptions { HttpMethod = "Post", UpdateTargetId = "searchresults" }))
{
#Html.TextBox("searchString")
<input type="submit" value="Search" />
}
<div id="searchresults">
</div>
</body>
</html>

Anti Forge Token and Ajax JSON Post Does not Work

I am running MVC3, .Net 4 and VS2010. I have following sample project to illustrate the problem.
My controller code
namespace AntiForgeAjaxTest.Controllers
{
public class IndexController : Controller
{
public ActionResult Index()
{
MyData d = new MyData();
d.Age = 20;
d.Name = "Dummy";
return View(d);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Index(MyData data)
{
NameValueCollection nc = Request.Form;
return View(data);
}
protected override void ExecuteCore()
{
base.ExecuteCore();
}
}
}
My view and JavaScript code
#model AntiForgeAjaxTest.Models.MyData
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<title>Index</title>
<script src="../../Scripts/jquery-1.5.1.js" type="text/javascript"></script>
<script src="../../Scripts/json2.js" type="text/javascript"></script>
</head>
<body>
#using (Html.BeginForm("Index", "Index"))
{
#Html.AntiForgeryToken()
<table>
<tr>
<td>Age</td>
<td>#Html.TextBoxFor(x => x.Age)</td>
</tr>
<tr>
<td>Name</td>
<td>#Html.TextBoxFor(x => x.Name)</td>
</tr>
</table>
<input type="submit" value="Submit Form" /> <input type="button" id="myButton" name="myButton" value="Ajax Call" />
}
<script type="text/javascript">
$(document).ready(function () {
$('#myButton').click(function () {
var myObject = {
__RequestVerificationToken: $('input[name=__RequestVerificationToken]').val(),
Age: $('#Age').val(),
Name: $('#Name').val(),
};
alert(JSON.stringify(myObject));
$.ajax({
type: 'POST',
url: '/Index/Index',
dataType: 'json',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(myObject),
success: function (result) {
alert(result);
},
error: function (request, error) {
alert(error);
}
});
});
});
</script>
</body>
</html>
Here I have 2 buttons, the first one triggers form post, the second one triggers Ajax post. The form post works fine, but the Ajax one does not, the server complains A required anti-forgery token was not supplied or was invalid. even though I have included the token in my JSON already.
Any idea what is wrong with my code?
This code works.
#model AntiForgeAjaxTest.Models.MyData
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<title>Index</title>
<script src="../../Scripts/jquery-1.5.1.js" type="text/javascript"></script>
<script src="../../Scripts/json2.js" type="text/javascript"></script>
</head>
<body>
#using (Html.BeginForm("Index", "Index"))
{
#Html.AntiForgeryToken()
<table>
<tr>
<td>Age</td>
<td>#Html.TextBoxFor(x => x.Age)</td>
</tr>
<tr>
<td>Name</td>
<td>#Html.TextBoxFor(x => x.Name)</td>
</tr>
</table>
<input type="submit" value="Submit Form" /> <input type="button" id="myButton" name="myButton" value="Ajax Call" />
}
<script type="text/javascript">
$(document).ready(function () {
$('#myButton').click(function () {
post();
});
});
function post() {
var myObject = {
__RequestVerificationToken: $('input[name=__RequestVerificationToken]').val(),
Age: $('#Age').val(),
Name: $('#Name').val(),
};
$.post('/Index/Index/', myObject);
}
</script>
</body>
</html>

Uploadify in MVC3 does not work

Can't get this to do anything. When I click 'Upload File' absolutely nothing happens as well as I don't see any of the flash rendered to the screen. I believe this is somehow related to the jquery, but I am not sure. PLEASE HELP! If someone can mail me a simple VS2010 solution with uploadify working to infinitimods at gmail.com that actually works I'd appreciate even more! Thanks a bunch!
My Layout file:
<!DOCTYPE html>
<html>
<head>
<title>#ViewBag.Title</title>
<link href="#Url.Content("~/Content/Site.css")" rel="stylesheet" type="text/css" />
<link type="text/css" rel="Stylesheet" media="screen" href="/Scripts/uploadify/uploadify.css" />
<script type="text/javascript" src="/Scripts/uploadify/swfobject.js"></script>
<script type="text/javascript" src="/Scripts/uploadify/jquery.uploadify.v2.1.4.min.js"></script>
<script type="text/javascript" src="/Scripts/uploadify/jquery-1.4.2.min.js"></script>
</head>
<body>
#RenderBody()
</body>
</html>
My index file:
#{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Index</h2>
#using (Html.BeginForm("UploadFile", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<script type="text/javascript">
$(document).ready(function () {
$("#file_upload").uploadify({
'uploader': '~/Scripts/uploadify/uploadify.swf',
'cancelImg': '~/Scripts/uploadify/images/cancel.png',
'buttonText': 'Upload foto',
'script': '/Home/UploadFiles',
'folder': '/Content/upload',
'fileDesc': 'Image Files',
'fileExt': '*.jpg;*.jpeg;*.gif;*.png; *.txt;',
'scriptData': { 'thisGuid': $("input#Id").val() },
'multi': false,
'auto': true,
'onError': function (event, queueID, fileObj, errorObj) {
alert("Error!!! Type: [" + errorObj.type + "] Info [" + errorObj.info + "]");
}
});
$("#btnSave").button().click(function (event) {
$('#file_upload').uploadifyUpload();
});
});
</script>
<input id="file_upload" type="file" />
<input type="button" id="btnSave" value="Upload file" />
<input id="Id" name="Id" type="hidden" value="5168e-yada-yada" />
}
My controller:
public class HomeController : Controller
{
/// <summary>
///
/// </summary>
/// <returns></returns>
[HttpGet]
public ActionResult Index()
{
return View("Index");
}
/// <summary>
///
/// </summary>
/// <param name="fileData"></param>
/// <param name="form"></param>
/// <returns></returns>
[HttpPost]
public string UploadFile(HttpPostedFileBase fileData, FormCollection form)
{
return "ok";
}
}
Uploadify requires jQuery. This means that you need to include the jQuery script before the uploadify script. If you had looked in your javascript debugging console you would have seen this error.
So, the layout:
<!DOCTYPE html>
<html>
<head>
<title>#ViewBag.Title</title>
<link href="#Url.Content("~/Scripts/uploadify/uploadify.css")" type="text/css" rel="stylesheet" media="screen" />
<script type="text/javascript" src="#Url.Content("~/Scripts/uploadify/swfobject.js")"></script>
<script type="text/javascript" src="#Url.Content("~/Scripts/uploadify/jquery-1.4.2.min.js")"></script>
<script type="text/javascript" src="#Url.Content("~/Scripts/uploadify/jquery.uploadify.v2.1.4.min.js")"></script>
</head>
<body>
#RenderBody()
</body>
</html>
The controller:
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult UploadFile(HttpPostedFileBase fileData, string thisGuid)
{
if (fileData != null && fileData.ContentLength > 0)
{
var appData = Server.MapPath("~/app_data");
var file = Path.Combine(appData, Path.GetFileName(fileData.FileName));
fileData.SaveAs(file);
}
return Json(new { status = true });
}
}
and the view:
#{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<script type="text/javascript">
$(document).ready(function () {
$('#file_upload').uploadify({
'uploader': '#Url.Content("~/Scripts/uploadify/uploadify.swf")',
'cancelImg': '#Url.Content("~/Scripts/uploadify/images/cancel.png")',
'buttonText': 'Select photo',
'script': $('form').attr('action'),
'fileDesc': 'Image Files',
'fileExt': '*.jpg;*.jpeg;*.gif;*.png; *.txt;',
'multi': false,
'auto': false,
'onError': function (event, queueID, fileObj, errorObj) {
alert("Error!!! Type: [" + errorObj.type + "] Info [" + errorObj.info + "]");
}
});
$('form').submit(function () {
$('#file_upload').uploadifySettings('scriptData', { thisGuid: $('#id').val() });
$('#file_upload').uploadifyUpload();
return false;
});
});
</script>
<h2>Index</h2>
#using (Html.BeginForm("UploadFile", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<input id="id" name="id" type="hidden" value="5168e-yada-yada" />
<input id="file_upload" type="file" name="fileData" />
<input type="submit" value="Upload file" />
}
And if you want to kick the uploading process when the user selects a photo you could get rid of the form and the submit button and set the auto property to true:
#{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<script type="text/javascript">
$(document).ready(function () {
$('#file_upload').uploadify({
'uploader': '#Url.Content("~/Scripts/uploadify/uploadify.swf")',
'cancelImg': '#Url.Content("~/Scripts/uploadify/images/cancel.png")',
'buttonText': 'Select photo',
'script': $('form').attr('action'),
'fileDesc': 'Image Files',
'fileExt': '*.jpg;*.jpeg;*.gif;*.png; *.txt;',
'multi': false,
'auto': true,
'scriptData': { thisGuid: $('#id').val() },
'onError': function (event, queueID, fileObj, errorObj) {
alert("Error!!! Type: [" + errorObj.type + "] Info [" + errorObj.info + "]");
}
});
});
</script>
<h2>Index</h2>
<input id="id" name="id" type="hidden" value="5168e-yada-yada" />
<input id="file_upload" type="file" name="fileData" />
Also don't forget to checkout the uploadify documentation to better understand what the different options are used for and also you can see some examples.
You need to work around a bug with asp.net and flash.
This article helped me once: Working around flash cookie bug
Maybe this is a better solution: jquery file upload

Resources