What to put in Inherits part in Partial in mvc3 - asp.net-mvc-3

i have in my controller and im not sure if i have it correct
[HttpGet]
[NoCache]
public ActionResult ListCommentsOnNews(int newsId, string newsComment) ???
{
//code here with return
}
in my Article.aspx view:
<div class="news-comment-content" id="news-comment-content">
<% if (Model.Results != null)
{ %>
<% foreach (var newsItem in Model.Results.NewsComments)
{ %>
<% Html.RenderPartial("SetCommentOnNews", newsItem); %>
<%} } %>
</div>
then my partial ListCommentsOnNews.ascx:
<%# Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<???>" %>
<div class="news-post-list-item">
<div class="news-post-user-info-wrapper">
<div class="avatar">
<img width="52" height="52" alt="Avatar" src="/ThemeFiles/Base/images/User/user-avatar.png" />
</div>
<div class="who-and-when-box">
<%: newsItem.CommentDate %> //get error here
<br />
<br />
<%: ViewBag.UserName %>
</div>
<div class="news-comment"><%: newsItem.NewsComment %></div> //and get error here
<div class="clear"></div>
</div>
<div class="clear"></div>
</div>
my controller:
[HttpGet]
public ActionResult Article(int id, int? page)
{
var news = ZincService.NewsService.GetNewsForId(id);
var allNewsComments = ZincService.NewsService.GetAllNewsCommentsForId(id, page.GetValueOrDefault(1), 10);
var currentUser = ZincService.GetUserForId(CurrentUser.UserId);
if (news == null || news.PublishingState != PublishingState.Live)
return RedirectToAction("NotFound");
if (allNewsComments != null)
{
var user = ZincService.GetUserForId(currentUser.UserId);
if (user == null || user.Customer.CustomerId != CurrentCustomer.CustomerId)
return DataNotFound();
ViewBag.Avatar = user.UserImage;
ViewBag.UserName = user.Firstname + " " + user.Surname;
NewsCommentsViewModel model = (NewsCommentsViewModel)SetNewsArticleViewModel(news, new NewsCommentsViewModel());
foreach (var newsItem in allNewsComments.NewsComments)
{
model.Results = allNewsComments;
model.PageSize = 10;
model.CurrentPage = page.GetValueOrDefault(1);
}
return View(model);
}
else
{
return View(SetNewsArticleViewModel(news,null));
}
}
[NonAction]
private NewsArticleViewModel SetNewsArticleViewModel(Entities.News.News news, NewsArticleViewModel viewModel)
{
viewModel.News = news;
viewModel.IsFavourite = ZincService.FavouriteService.IsFavouriteForUser(CurrentUser.UserId, news);
viewModel.DownloadAttachments = news.NewsAttachments.Where(x =>
Core.FileFormat.FileFormatHelper.GetFileFormatType(x.FileExtension) == Core.FileFormat.FileFormatType.Excel ||
Core.FileFormat.FileFormatHelper.GetFileFormatType(x.FileExtension) == Core.FileFormat.FileFormatType.PDF ||
Core.FileFormat.FileFormatHelper.GetFileFormatType(x.FileExtension) == Core.FileFormat.FileFormatType.PowerPoint ||
Core.FileFormat.FileFormatHelper.GetFileFormatType(x.FileExtension) == Core.FileFormat.FileFormatType.Word);
viewModel.EmbedAttachments = news.NewsAttachments.Where(x =>
Core.FileFormat.FileFormatHelper.GetFileFormatType(x.FileExtension) == Core.FileFormat.FileFormatType.Video);
return viewModel;
}
i get errors on the newsItem parts stating that it does not exist in the current context.
can some one help me right please?

As i inferred from code you posted, problem is with you'r usage of Model.you are trying to use model properties,but you are not doing it correctly.try following :
<%
Model.CommentDate
%>
instead of
<%: newsItem.CommentDate %> //get error here

Related

Sitefinity 11 Can't get dropdown selected value on postback in Frontend Widget Control

I am using Sitefinity 11. I have created a Custom Widget for News Module, having Drop down for all available Categories, where I need to filter the News for Selected Category. The Control postback's but it's SelectedIndex is always ZERO.
I have checked the checkbox for "Enable View State for this page" and Page is using custom Layout Template.
The code in my .aspx file is given below:
<%# Control Language="C#" %>
<%# Import Namespace="Telerik.Sitefinity.Modules.News" %>
<%# Import Namespace="Telerik.Sitefinity.Taxonomies.Model" %>
<%# Import Namespace="Telerik.Sitefinity.Model" %>
<%# Register TagPrefix="sf" Namespace="Telerik.Sitefinity.Web.UI.ContentUI" Assembly="Telerik.Sitefinity" %>
<%# Register TagPrefix="sf" Namespace="Telerik.Sitefinity.Web.UI.Comments" Assembly="Telerik.Sitefinity" %>
<%# Register TagPrefix="sf" Namespace="Telerik.Sitefinity.Web.UI" Assembly="Telerik.Sitefinity" %>
<%# Register TagPrefix="telerik" Namespace="Telerik.Web.UI" Assembly="Telerik.Web.UI" %>
<%# Register TagPrefix="sf" Namespace="Telerik.Sitefinity.Web.UI.PublicControls.BrowseAndEdit" Assembly="Telerik.Sitefinity" %>
<script type="C#" runat="server">
protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack)
{
try
{
var ControlID = Request.Form["__EVENTTARGET"].ToString();
Control postbackControl = Page.FindControl(ControlID);
lblStatus.Text = "ControlID=" + ControlID + "<br>";
DropDownList dd = (DropDownList)postbackControl;
lblStatus.Text += "SelectedIndex=" + dd.SelectedIndex.ToString();
}
catch (Exception ex) {
lblStatus.Text += "<br>" + ex.Message;
}
}
var s = ddlCategories.SelectedIndex;
if (!IsPostBack)
{
/* List of all categories */
Telerik.Sitefinity.Taxonomies.TaxonomyManager manager1 = Telerik.Sitefinity.Taxonomies.TaxonomyManager.GetManager();
System.Collections.IList categoryList = manager1.GetTaxa<Telerik.Sitefinity.Taxonomies.Model.HierarchicalTaxon>()
.Where(t => t.Taxonomy.Title == "Categories")
.Select(t =>
new { Id = t.Id, Name = t.Title.ToString() })
.OrderByDescending(t => t.Name)
.ToList();
ddlCategories.DataSource = categoryList;
ddlCategories.DataTextField = "Name";
ddlCategories.DataValueField = "Id";
ddlCategories.DataBind();
ddlCategories.Items.Insert(0, new ListItem("", ""));
}
}
protected void DdlCategories_SelectedIndexChanged(object sender, EventArgs e)
{
Telerik.Sitefinity.Modules.News.NewsManager newsManager = Telerik.Sitefinity.Modules.News.NewsManager.GetManager();
if (this.ddlCategories.SelectedIndex > 0)
{
//this.FilterExpression += string.Format(" AND Category.Contains(({0}))", this.ddlCategories.SelectedValue.ToString());
Guid taxonFilter = new Guid(this.ddlCategories.SelectedValue.ToString());
NewsList.DataSource = newsManager.GetNewsItems().Where(newsItem => newsItem.Status == Telerik.Sitefinity.GenericContent.Model.ContentLifecycleStatus.Live
&& newsItem.GetValue<IList<Guid>>("Categories")
.Contains(taxonFilter)
).ToList();
}else {
NewsList.DataSource = newsManager.GetNewsItems().Where(newsItem => newsItem.Status == Telerik.Sitefinity.GenericContent.Model.ContentLifecycleStatus.Live).ToList();}
//populate items list
//return base.GetItemsList(ref totalCount);
}
</script>
<section class="news-container">
<div class="container">
<asp:Label ID="lblStatus" runat="server"></asp:Label>
<!-- filter panel -->
<div class="filter-panel">
<div class="panel-box categories">
<span class="label">CATEGORIES</span>
<div class="select-wrp">
<asp:DropDownList ID="ddlCategories" runat="server" AutoPostBack="true" OnSelectedIndexChanged="DdlCategories_SelectedIndexChanged">
<asp:ListItem></asp:ListItem>
</asp:DropDownList>
</div>
</div>
</div>
</div>
<sf:SitefinityLabel id="title" runat="server" WrapperTagName="div" HideIfNoText="true" HideIfNoTextMode="Server" />
<telerik:RadListView ID="NewsList" ItemPlaceholderID="ItemsContainer" runat="server" EnableEmbeddedSkins="false" EnableEmbeddedBaseStylesheet="false">
<LayoutTemplate>
<div class="container extra-container2">
<div class="row news-post">
<asp:PlaceHolder ID="ItemsContainer" runat="server" />
</div>
</div>
</LayoutTemplate>
<ItemTemplate>
<article class="col-12 col-sm-6 col-md-6 col-lg-4 post">
<div class="holder">
<h2><sf:FieldListView ID="Title" runat="server" Text="{0}" Properties="Title" TextMode="Encode" EditableFieldType="ShortText"/> </h2>
</div>
</article>
</ItemTemplate>
</telerik:RadListView>
<sf:Pager id="pager" runat="server"></sf:Pager>
<asp:PlaceHolder ID="socialOptionsContainer" runat="server" />
</section>
EDIT: Even following code is getting the same result.
protected void Page_Load(object sender, EventArgs e)
{
//if (!IsPostBack)
{
/* List of all categories */
Telerik.Sitefinity.Taxonomies.TaxonomyManager manager1 = Telerik.Sitefinity.Taxonomies.TaxonomyManager.GetManager();
System.Collections.IList categoryList = manager1.GetTaxa<Telerik.Sitefinity.Taxonomies.Model.HierarchicalTaxon>()
.Where(t => t.Taxonomy.Title == "Categories")
.Select(t =>
new { Id = t.Id, Name = t.Title.ToString() })
.OrderByDescending(t => t.Name)
.ToList();
ddlCategories.DataSource = categoryList;
ddlCategories.DataTextField = "Name";
ddlCategories.DataValueField = "Id";
ddlCategories.DataBind();
ddlCategories.Items.Insert(0, new ListItem("", ""));
}
if (Page.IsPostBack)
{
try
{
var ControlID = Request.Form["__EVENTTARGET"].ToString();
Control postbackControl = Page.FindControl(ControlID);
lblStatus.Text = "ControlID=" + ControlID + "<br>";
DropDownList dd = (DropDownList)postbackControl;
lblStatus.Text += "SelectedIndex=" + dd.SelectedIndex.ToString();
}
catch (Exception ex) {
lblStatus.Text += "<br>" + ex.Message;
}
}
var s = ddlCategories.SelectedIndex;
}
please guide me what is missing?
Thanks
Make sure the page has Enable Viewstate checked - this is in the Title and Properties of the page
I have added a Hidden Field and I was able to get it's value after postback. Another solution was to send value in query-string.
Thanks for all replies.

How to make use of Viewbag in my View

I dont understand, I have my in my Controller:
[HttpGet]
public ActionResult Detail(int userId)
{
var user = ZincService.GetUserForId(userId);
if (user != null)
{
ViewBag.user = userId;
ViewBag.email = user.Email;
ViewBag.title = user.JobTitle;
ViewBag.node = user.Node;
}
return View(user);
}
then my view, Detail.aspx
<div id="user-details-view">
<div>
Title:
</div>
<div>
<%: Model.JobTitle %>
<%: Model.News %>
<%: Model.Node %>
</div>
<div>
<%: Html.ActionLink("Change Email Address", "ChangeEmailAddress", new { #id = Model.UserId })%>
</div>
</div>
when I run my app i get an error:
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: /Areas/Admin/Views/User/Detail.aspx
I dont understand? Is it because of syntax errors?
Previous posts are correct as in logic but you assigned the viewbag names in your controller differently. It should be:
<div id="user-details-view">
<div>
Title:
</div>
<div>
<%: ViewBag.email %>
<%: ViewBag.title %>
<%: ViewBag.node %>
</div>
<div>
<%: Html.ActionLink("Change Email Address", "ChangeEmailAddress", new { #id = ViewBag.user })%>
</div>
</div>
Hope it helps..
It must be like this
<%: ViewBag.JobTitle %>
<%: ViewBag.News %>
<%: ViewBag.Node %>
Replace the Model. with ViewBag.
<%: ViewBag.title %>
<%: ViewBag.email %>
<%: ViewBag.node %>
and also change this
<%: Html.ActionLink("Change Email Address", "ChangeEmailAddress", new { id = ViewBag.user })%>
You must use that sintax:
<%: ViewBag.email %>
<%: ViewBag.title %>
<%: ViewBag.node %>
But would be better if you use Model:
public class UserInfo
{
public int UserId { get; set; }
public string Email { get; set; }
public string Title { get; set; }
public NodeType Node { get; set; }
}
[HttpGet]
public ActionResult Detail( int userId )
{
var data = ZincService.GetUserForId( userId );
var user = new UserInfo();
if ( data != null )
{
user.UserId = userId;
user.Email = data.Email;
user.Title = data.JobTitle;
user.Node = data.Node;
}
return View( user );
}
In view (MVC3) with razor sintax:
#model UserInfo
<div id="user-details-view">
<div>
Title:
</div>
<div>
#Model.Title
#Model.Node
</div>
<div>
#Html.ActionLink("Change Email Address", "ChangeEmailAddress", new { #id = Model.UserId })
</div>
</div>

Return Succes Message After Delete/Update/create

This is my GesAgence Page action :
public ActionResult GesAgence()
{
var test = new Models.J2VEntities();
return View(test.agence);
}
This is my Action for Deleting :
public ActionResult DeleteAg(string id)
{
Models.J2VEntities entity = new Models.J2VEntities();
Models.agence model = (from p in entity.agence
where p.Idag == id
select p).SingleOrDefault();
//Sauvgarde ds la BD
entity.agence.DeleteObject(model);
entity.SaveChanges();
return View("gesAgence");
}
So i'm wondring how to return Succes message after deleting(i tried with TempData but didn't succed because my gesAgence must return model not TempData).
You can use Ajax to call your controller from your viewpage and pop up the message whatever your controller returned, try something like this.
Script on your view page.
function onDeleteAg (id) {
var answer = confirm("Are you sure you want to delete AG ?")
if (answer) {
$.ajax(
{
type: "Get",
url: '<%= Url.Action("DeleteAg","YourControllerName") %>',
data: { agId: id },
success: function (data) {
//HERE--data is the message you that your controller DeleteAg method will return after it's called. you need to do something here to display this message(data) anywhere you want to . something like below.
alert(data);
},
error: (function () { alert("Error! Ag was not deleted." ); })
});
}
};
Method on your controller.
public string DeleteAg(string agId)
{
try{
Models.J2VEntities entity = new Models.J2VEntities();
Models.agence model = (from p in entity.agence
where p.Idag == id
select p).SingleOrDefault();
//Sauvgarde ds la BD
entity.agence.DeleteObject(model);
entity.SaveChanges();
}
catch(Exception ex)
{
return "AG has not been deleted successfully;
}
return "AG has been deleted successfully;
}
you can call this method via ajax and return JsonResult instead of ActionResult, by looking result you can show message to user.
public JsonResult DeleteAg(string id)
{
Models.J2VEntities entity = new Models.J2VEntities();
Models.agence model = (from p in entity.agence
where p.Idag == id
select p).SingleOrDefault();
//Sauvgarde ds la BD
entity.agence.DeleteObject(model);
entity.SaveChanges();
var json = new
{
success = true
};
return Json(json);
}
You can set Success to ViewBag
public ActionResult DeleteAg(string id)
{
Models.J2VEntities entity = new Models.J2VEntities();
Models.agence model = (from p in entity.agence
where p.Idag == id
select p).SingleOrDefault();
//Sauvgarde ds la BD
entity.agence.DeleteObject(model);
entity.SaveChanges();
ViewData["Success"] = true;
return View("gesAgence");
}
in view
#if(ViewData["Success"] != null && (bool)ViewData["Success"]){
<script>alert("Sucess!");</script>
}
This is my view :
<% if(ViewData != null && ViewData["Success"] != null && (bool)ViewData["Success"]){ %>
<script type="text/javascript"> alert("Sucess!");</script>
<% } %>
<div class="clear">
</div>
<div id="main">
<h1> Demande preinscrit</h1>
<ul class="listing">
<% foreach (var item in Model) { %>
<li>
<div class="listinfo">
<h3>
<%: Html.DisplayFor(modelItem => item.Nomag) %>
</h3>
<p>
<%: Html.DisplayFor(modelItem => item.Idag) %>
</p>
<span class="price"> <%: Html.DisplayFor(modelItem => item.Adrag) %> <%: Html.DisplayFor(modelItem => item.Vilag) %> <%: Html.DisplayFor(modelItem => item.Gov) %></span> <span class="media">Tel : <%: Html.DisplayFor(modelItem => item.Telag) %> |</span> <%: Html.DisplayFor(modelItem => item.Mailag) %>
</div>
<div class="listingbtns">
<span class="listbuttons"><%: Html.ActionLink("Bloque", "Bloque", new {id= item.Idag}) %> </span>
<span class="listbuttons"><%: Html.ActionLink("Supprime", "DeleteAg", new { id = item.Idag })%></span>
</div>
<div class="clear">
</div>
</li>
<% } %>
i got this error : System.NullReferenceException: Object reference not set to an instance of an object on this line <% foreach (var item in Model) { %>.

How can I reload only part of page

My page which for online shoping, contains two parts. First part is a list of products.
#model WebUI.Models.CakesListViewModel
#foreach (var p in Model.Cakes) {
Html.RenderPartial("CakesList", p);
}
Each product appears as partial view. CakesList.cshtml
#model Domain.Entities.Cake
<div>
#if (Model.ImageData != null) {
<div style="float:left;margin-right:20px">
<img width="75" height="75" src="#Url.Action("GetImage", "Cake", new { Model.Id })" />
</div>
}
<b>#Model.Name<br />
#Model.Price</b><br />
#Model.Description
#using (Html.BeginForm("AddToCart", "Cart"))
{
#Html.HiddenFor(x => x.Id)
#Html.TextBox("quantity", "", new { style = "width: 20px; text-align: center" })
<input type="image" src="../Images/basket.jpg" />
}
</div>
All page is reloading, after clicking basket image button, but I need to reload only second part of page. How can I do it.
Second part is sum of ordered products.
#model Domain.Entities.Cart
#{
Layout = null;
string str = String.Format("{0}", Model.ComputeTotalValue());
}
<div id="cart">
#Html.ActionLink(str, "Index", "Cart")
</div>
Which is appeared from _Layout.cshtml
</head>
<body>
<div id="header">
#{Html.RenderAction("Summary", "Cart");}
<div class="title">Cakes</div>
</div>
<div id="categories">
#{ Html.RenderAction("Menu", "MenuItems"); }
</div>
<div id="content">
#RenderBody()
</div>
</body>
</html>
//CakeController
namespace WebUI.Controllers
{
public class CakeController : Controller
{
public int PageSize = 4;
private ICakeRepository repository;
public CakeController(ICakeRepository cakeRepository)
{
repository = cakeRepository;
}
public FileContentResult GetImage(int id)
{
Cake prod = repository.Cakes.FirstOrDefault(p => p.Id == id);
if (prod != null)
return File(prod.ImageData, prod.ImageMimeType);
else
return null;
}
public ActionResult OnlineShop(string regions, int page = 1)
{
CakesListViewModel viewModel = new CakesListViewModel
{
Cakes = repository.Cakes
.Where(p => regions == null || p.Name.Trim() == regions),
PagingInfo = new PagingInfo
{
CurrentPage = page,
ItemsPerPage = PageSize,
TotalItems = 1
},
CurrentCategory = "category"
};
return View("OnlineShop", viewModel);
}
}
}
//OnlineShop.cshtml
#model WebUI.Models.CakesListViewModel
#{
ViewBag.Title = "Cakes";
}
#foreach (var p in Model.Cakes) {
Html.RenderPartial("CakesList", p);
}
//CakesList.cshtml
#model Domain.Entities.Cake
#if (Model.ImageData != null) {
<div style="float:left;margin-right:20px">
<img width="75" height="75" src="#Url.Action("GetImage", "Cake", new { Model.Id })" />
</div>
}
<b>#Model.Name<br />
#Model.Price</b><br />
#Model.Description
#using (Ajax.BeginForm("AddToCart", "Cart", new AjaxOptions { HttpMethod = "Get", InsertionMode = InsertionMode.Replace, UpdateTargetId = "mydiv" }))
{
#Html.HiddenFor(x => x.Id)
#Html.TextBox("quantity", "", new { style = "width: 20px; text-align: center" })
<input type="image" src="../Images/basket.jpg" />
}
//CartController
namespace WebUI.Controllers
{
public class CartController : Controller
{
private ICakeRepository repository;
private IOrderProcessor orderProcessor;
public CartController(ICakeRepository repo, IOrderProcessor proc)
{
repository = repo;
orderProcessor = proc;
}
public ActionResult AddToCart(Cart cart, int id, int quantity = 1)
{
Cake cake = repository.Cakes.FirstOrDefault(p => p.Id == id);
if (cake != null)
cart.AddItem(cake, quantity);
return RedirectToAction("OnlineShop", "Cake");
}
public ActionResult RemoveFromCart(Cart cart, int id)
{
Cake cake = repository.Cakes.FirstOrDefault(p => p.Id == id);
if (cake != null)
cart.RemoveLine(cake);
return RedirectToAction("Index", "Cart");
}
public ViewResult Index(Cart cart, string returnUrl)
{
return View(new CartIndexViewModel
{
Cart = cart,
ReturnUrl = returnUrl
});
}
public ViewResult Summary(Cart cart)
{
return View(cart);
}
}
}
//Summary.cshtml
#model Domain.Entities.Cart
#{
Layout = null;
string str = String.Format("{0}", Model.ComputeTotalValue());
}
<div id="cart">
<p>
<img src="../Images/basket.jpg" />
<div id="mydiv">#Html.ActionLink(str, "Index")</div>
</p>
</div>
<h2>About</h2>
<p>
Put content here.
</p>
#Ajax.ActionLink("Link Text", "ActionThatWillReturnContent", new AjaxOptions
{
HttpMethod = "GET",
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "ContainerThatIWillUpdate"
})
<div id="ContainerThatIWillUpdate"></div>
This will call "ActionThatWillReturnContent" and insert content inside of "ContainerThatIWillUpdate".
Alternative is to use jQuery.ajax which is a lot nicer, but will require a little reading/playing around with.
Update 1:
You send an AJAX request to your action method called AddToCart. This method does some processing and then returns a full view:
return RedirectToAction("OnlineShop", "Cake");
What you want to do, is return a partial view, that will be placed inside of "mydiv", which is your update target id.
Your action method needs to be modified to return PartialView, rather than ActionResult:
public PartialViewResult AddToCart(Cart cart, int id, int quantity = 1)
{
// Inside this action method, you don't want to return a redirect to action,
// you want to return partial view
return PartialView(); // This has three constructors, so you'll need to do a bit of digging.
}

MVC3 - When using HttpPostedFileBase with large files, RedirectToAction is very slow

Okay, I have a situation that seems to make no sense. I have a controller thus:
public ActionResult Index()
{
return View(_courseService.ListAllCourses());
}
[HttpPost]
public ActionResult CreateNewCourse(CourseVDO course, HttpPostedFileBase CourseDataFile)
{
return RedirectToAction("Index");
}
And a View thus:
#using (Html.BeginForm("CreateNewCourse", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
#Html.ValidationSummary(false)
<fieldset>
<legend>Course</legend>
<div class="editor-label">
#Html.LabelFor(model => model.Name)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Name)
#Html.ValidationMessageFor(model => model.Name)
</div>
<div class="editor-label">
Course Data File
</div>
<div class="editor-field">
<input type="file" name="CourseDataFile" id="CourseDataFile" />
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Visible)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Visible)
#Html.ValidationMessageFor(model => model.Visible)
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
When I submit a file of around 200KB, it uploads to the server fast enough (it's local after all), but then takes 5 seconds to go from the "return RedirectToAction("Index"); " line back to the breakpoint on the "return View(_courseService.ListAllCourses());" line (not actually executing the ListAllCourses). This means it's entirely down to the internal plumbing. Worse, this delay scales with file size. What on earth is going on, and how can I stop it?
Thanks
I have never used that method before, and this is no direct answer, but maybe its a better solution:
// used when editing an item
public void UploadFiles(FormCollection form, NameValueCollection currentFiles, string folder, bool useTicks)
{
foreach (string file in Request.Files)
{
var hpf = Request.Files[file];
if (hpf.ContentLength == 0)
{
form[file] = currentFiles[file];
}
else
{
var filename = useTicks ? hpf.FileName
.Replace(" ", "_")
.Replace(".", RandomFileName() + ".") : hpf.FileName;
var myPath = Server.MapPath("~/Content/" + folder);
hpf.SaveAs(myPath + "/" + filename);
form[file] = filename;
}
}
if (Request.Files.Count > 0) return;
foreach (var file in currentFiles.AllKeys)
{
form[file] = currentFiles[file];
}
}
//used when creating a new item
public void UploadFiles(FormCollection form, string folder, bool useTicks)
{
foreach (string file in Request.Files)
{
var hpf = Request.Files[file];
if (hpf.ContentLength == 0)
{
form[file] = null;
}
else
{
var filename = "";
filename = useTicks ?
hpf.FileName.Replace(" ", "_").Replace(".", RandomFileName() + ".") :
hpf.FileName;
UploadFileName = filename;
var myPath = Server.MapPath("~/Content/" + folder);
hpf.SaveAs(myPath + "/" + filename);
form[file] = UploadFileName;
}
}
}
I use models so in my model item i use the UIHint("uploadbox")
here is the code inside views/Shared/EditorTemplates/UploadField.cshtml
#Html.TextBox("",null,new{type="File"})
here is an example of the usage of the upload feature:
public ActionResult AddFiles(FormCollection form, SomeModel myModel)
{
UploadFiles(form,"products", true);
myModel.pdfFile = form["pdffile"];
myModel.thumbnail = form["thumbnail"];
here is the code when editing the item, in case the file was not changed, but others items have
var existingFile = ctx2.modelname.SingleOrDefault(x => x.Id == id).Filename;
NameValueCollection myCol = new NameValueCollection();
myCol.Add("Filename", existingFile);
UploadFiles(form, myCol, "uploads/custom", true);
myModel.Filename = form["Filename"];
just a thought :-)

Resources