how to delete previusly selected file based on index value in mvc3? - asp.net-mvc-3

Hi all i am working on mvc3
here i need to delete a previously uploaded file from the sessions data
anh i am displaying the file before inserting into data base so i am displaying the data in sessions now i need to delete the previously selected file plz help to how to get the selected file index value to delete the file from the sessions
For example here check this post it is in c# but i need this is in mvc3 please help me to do this work plz help me anyone
here my models are
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
namespace BugTracker.Models
{
public class BugModel
{
public BugModel()
{
if (ListFile == null)
ListFile = new List<BugAttachment>();
}
public List<BugAttachment> ListFile { get; set; }
public string ErrorMessage { get; set; }
}
public class BugAttachment
{
public string FileName { get; set; }
public int BugAttachmentID { get; set; }
public string AttachmentName { get; set; }
public int BugID { get; set; }
public string AttachmentUrl { get; set; }
public string AttachedBy { get; set; }
}
}
here my controllers
public ActionResult UploadFile(string AttachmentName, BugModel model)
BugModel bug = null;
if (Session["CaptureData"] == null)
{
bug = model;
}
else
{
bug = (BugModel)Session["CaptureData"];
}
foreach (string inputTagName in Request.Files)
{
HttpPostedFileBase file1 = Request.Files[inputTagName];
if (file1.ContentLength > 0)
{
BugAttachment attachment = new BugAttachment();
var allowedExtensions = new[] { ".doc", ".xlsx", ".txt", ".jpeg", ".docx" };
var extension = Path.GetExtension(file1.FileName);
if (!allowedExtensions.Contains(extension))
{
model.ErrorMessage = "{ .doc, .xlsx, .txt, .jpeg }, files are allowed.... ";
}
else
{
string filename = Guid.NewGuid() + Path.GetFileName(file1.FileName);
string path = "/Content/UploadedFiles/" + filename;
string savedFileName = Path.Combine(Server.MapPath("~" + path));
file1.SaveAs(savedFileName);
attachment.FileName = "~" + path.ToString();
attachment.AttachmentName = AttachmentName;
attachment.AttachmentUrl = attachment.FileName;
bug.ListFile.Add(attachment);
model = bug;
}
Session["CaptureData"] = model;
}
}
ModelState.Clear();
return View("LoadBug", bug);
}
and here my view page
<div class="UploadMain">
<%:Html.Label("Attachment Name:") %>
<%:Html.TextBoxFor(model=>model.AttachmentName) %>
<span>
<%:Html.Label("Upload Files") %></span>
<input type="file" name="file" id="file" />
<input type="submit" value="Upload" id="Upload" class="style-name cancel" />
<%--onclick="window.location.href='<%= Url.Action("UploadFile", "Bug") %>';"--%>
<table align="center" class="gridtable" border="0" cellspacing="0" cellpadding="0">
<tr>
<th>
Attachment Name
</th>
<th>
Attachment Url
</th>
<th>
Action
</th>
</tr>
<% if (Model != null && Model.ListFile != null)
{ %>
<% foreach (var Emp in Model.ListFile)
{ %>
<tr class="Data">
<td >
<%:Emp.AttachmentName %>
</td>
<td >
<%: Emp.FileName %>
</td>
<td>
<%-- <%= Html.ActionLink("Delete", "Delete")%>--%>
<%:Html.ActionLink("Delete", "Delete", new { #FileName = Emp.FileName })%>
</td>
</tr>
<% } %>
<% } %>
</table>
</div>
For example here check this post it is in c# but i need this is in mvc3 please help me to do this work plz help me anyone
thanks in advance

To delete a file you uploaded all you need is its filepath, and use File.Delete("filepath");
To know which file to delete your Delete action should take an id:
Delete(int id)
Then in your action link pass the BugAttachmentID: (using route values/parameters)
<%:Html.ActionLink("Delete", "Delete", new { #FileName = Emp.FileName }, new { id = Emp.BugAttachmentID })%>
Then in your delete method you use the ID to find the file in the FileList you want to delete. And then call File.Delete using the attachment url.
I hope this helps.

Related

ASP.Net MVC Paging returns one large resultset instead of splitting resultset into pages

I am using Paging in my View and originally my #model was of type PagedList.IPagedList but I was having issues posting back the IPagedList interface back to controller, therefore, I found a post that gave a hint on how to deconstruct my IPagedList so I could present it in the View and be able to post back to controller for further processing as well. However, I ran into the following issue - I want to display only 50 records on each page. The search criteria I am testing returns 13000 records. I am expecting only 50 records on first page with page numbers 1,2,3 at bottom. I see the page numbers as expected at the bottom but all 13000 records get displayed on every page. I have debugged the code and found out that StaticPagedList function is returning 13000 records instead of 50 so I applied Skip and Take on the object before returning it to the View but the issue is still occurring. My code:
View Models -
public class PagedClientViewModel
{
public int? Page { get; set; }
public IEnumerable<SelectTimeTrackerEditorViewModel> Clients { get; set; }
public IPagedList PagingMetaData { get; set; }
}
public class SelectTimeTrackerEditorViewModel
{
public bool Selected { get; set; }
public int SID { get; set; }
public string PerNo { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
View -
#model EmergencyResponseTimeEntry.Models.PagedClientViewModel
#using PagedList;
#using PagedList.Mvc;
#foreach (var item in Model.Clients)
{
<tr>
<td>
#Html.CheckBoxFor(modelItem => item.Selected)
</td>
<td>
#Html.DisplayFor(modelItem => item.PerNo)
</td>
<td>
#Html.DisplayFor(modelItem => item.FirstName)
</td>
<td>
#Html.DisplayFor(modelItem => item.LastName)
</td>
</tr>
}
Page #(Model.PagingMetaData.PageCount < Model.PagingMetaData.PageNumber ? 0 : Model.PagingMetaData.PageNumber) of #Model.PagingMetaData.PageCount
#Html.PagedListPager(new StaticPagedList<EmergencyResponseTimeEntry.Models.SelectTimeTrackerEditorViewModel>(Model.Clients, Model.PagingMetaData), page => Url.Action("Index", new { page }), new PagedListRenderOptions { DisplayEllipsesWhenNotShowingAllPageNumbers = false})
Controller -
var list = (from c in timeTrackers
select new SelectTimeTrackerEditorViewModel
{
Selected = false,
SID = c.SID,
PerNo = c.PerNo,
FirstName = c.FirstName,
LastName = c.LastName
});
var pagedClientViewModel = new PagedClientViewModel
{
Clients = list
};
int pageSize = 50;
int pageNumber = (page ?? 1);
int totalClients = list.Count();
// List of current page of 50 records (hits database again, pulls only 50 records, though)
var timeTrackerList = list.Skip((pageNumber - 1) * pageSize).Take(pageSize).ToList();
pagedClientViewModel.PagingMetaData = new StaticPagedList<SelectTimeTrackerEditorViewModel>
(timeTrackerList, pageNumber, pageSize, totalClients).GetMetaData();
return View(pagedClientViewModel);
I got it working after co-worker pointed out that I was displaying all records in my view - Model.Clients. So in my controller, I changed this
var pagedClientViewModel = new PagedClientViewModel
{
Clients = list
};
to this -
var pagedClientViewModel = new PagedClientViewModel
{
Clients = list.Skip((pageNumber - 1) * pageSize).Take(pageSize).ToList()
};
Now paging is working as expected!

Set enum values as selected in Razor dropdown

I am using a razor view for showing the scored of an examination and it contains an enum value that holds 3 values "pass","Fail","absent" and i want to choose it accordingly. The model i used is
model
public class VerifyResultModel
{
[Display(Name = "StudnetId")]
public int StudentId { get; set; }
[Display(Name = "Student")]
[Required]
public string Student { get; set; }
[Display(Name = "Mark")]
[Required]
public int Mark { get; set; }
[Display(Name = "Score")]
[Required]
public string Score { get; set; }
[Display(Name = "Result")]
public App.EnumValues.ExamResultStatus Result { get; set; }
}
Controller
[HttpGet]
public ActionResult Verify(int Id)
{
List<VerifyResultModel> model_result = new List<VerifyResultModel>();
VerifyResultModel _resultItem;
foreach (exammark item in marks)
{
SchoolApp.EnumValues.ExamResultStatus result = SchoolApp.EnumValues.ExamResultStatus.Absent;
if(item.Mark >= MinMark)
{
result= SchoolApp.EnumValues.ExamResultStatus.Pass;
}
else
{
result = App.EnumValues.ExamResultStatus.Fail;
}
_resultItem = new VerifyResultModel { StudentId = (int)item.StudentId, Student = item.studentmaster.StudentName, Mark = (int)item.Mark, Score = item.Mark.ToString(), Result = result };
model_result.Add(_resultItem);
}
LoadResultsDropdown();
return View(model_result);
}
private void LoadResultsDropdown()
{
var types = (from App.EnumValues.ExamResultStatus type in Enum.GetValues(typeof(SchoolApp.EnumValues.ExamResultStatus))
select new { Id = type.ToString(), Name = type.ToString() }).ToList();
ViewBag.ResultList = new SelectList(types, "Id", "Name");
}
View
#model IList<SchoolApp.ViewModels.VerifyResultModel>
<tbody>
#for (int item = 0; item < Model.Count(); item++)
{
<tr>
<td>
#Html.DisplayFor(modelItem => Model[item].Student)
</td>
<td>
#Html.DisplayFor(modelItem => Model[item].Mark)
</td>*#
<td>
#Html.DisplayFor(modelItem => Model[item].Score)
</td>
<td>
#Html.DropDownListFor(model => model[item].Result, (SelectList)ViewBag.ResultList) //Here All values are showing as Pass ( first item in dropdown)
</td>
</tr>
}
</tbody>
The problem is even if i pass values Fail / Absent to enum it shows as Pass in combobox . How can i show the correct value ?
Can you please try this:
private void LoadResultsDropdown()
{
var types = (from App.EnumValues.ExamResultStatus type in Enum.GetValues(typeof(SchoolApp.EnumValues.ExamResultStatus))
select new { Id = type.ToString(), Name = type.ToString() }).ToList();
var types=Enum.GetValues(typeof(ExamResultStatus)).Cast<ExamResultStatus>();
var EnumData= types.Select(c => new { c.Key, c.Value });
ViewBag.ResultList = new SelectList(types.AsEnumerable(), "key", "value");
}
Hope this helps..

Foreach through IEnumerable in view

can someone help please, dont know what I am doing wrong:
my viewmodel:
public class ScormModuleViewModel
{
public IEnumerable<ScormModuleInfo> ScormModuleInfo { get; set; }
public int CurrentPage { get; set; }
public int PageSize { get; set; }
public double Total { get; set; }
public int RecordsPerPage { get; set; }
}
then my controller:
public ActionResult Index(int? page)
{
List<ScormModuleInfo> modules = new List<ScormModuleInfo>();
foreach (var directory in Directory.EnumerateDirectories(scormRootDir))
{
ScormModuleInfo module = new ScormModuleInfo();
module.ScormModule = ZincService.ScormService.GetScormModule(scormTitle, scormDirectory);
if (module.ScormModule != null)
module.Installed = true;
else
{
module.Installed = false;
module.ScormModule = new ScormModule();
module.ScormModule.Directory = scormDirectory;
module.ScormModule.Title = scormTitle;
}
module.ScormModule.EntryPointRef = scormEntryPointRef;
module.ScormModule.IdentifierRef = scormIdentifierRef;
module.ScormModule.LaunchHeight = scormLaunchHeight;
module.ScormModule.LaunchWidth = scormLaunchWidth;
module.ScormModule.LaunchResize = scormLaunchResize;
module.ScormModule.RelativeHtmlPath = scormRelativeHtmlPath;
module.ScormModule.SchemaVersion = scormSchemaVersion;
if (module.Installed)
{
// TODO: Save changes to module
//ZincService.ScormService.UpdateScormModuleSettings(
}
modules.Add(module);
noOfScormPackages++ ;
}
}
ScormModuleViewModel model = new ScormModuleViewModel();
model.ScormModuleInfo = modules;
model.CurrentPage = page.GetValueOrDefault(1);
model.PageSize = PageSizeSettings.ScormPackages;
model.Total = noOfScormPackages;
// Now iterate over modules and read imsmanifest.xml file for details of entry point and resources required.
return View(model);
}
and my view:
<%# Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<List<Zinc.Web.Areas.Admin.ViewModels.Scorm.ScormModuleViewModel>>" %>
foreach (var module in Model)
{ %>
<li>
<div class="col1">
<a href='javascript:LoadTrainingModuleWithDedicatedAPIObj("<%= module.ScormModuleInfo.r .sc.ScormModule.RelativeHtmlPath %>/<%= module.ScormModule.EntryPointRef %>", "<%: module.ScormModule.Title %>", "<%: module.ScormModule.LaunchWidth %>", "<%: module.ScormModule.LaunchHeight %>");'>
<% if (module.ScormModule.Title.Length < 70)
{ %>
<%: module.ScormModule.Title%>
<% }
else
{ %>
<%: module.ScormModule.Title.Substring(0, 70)%>....
<% } %>
</a>
</div>
i get redlines under all the module. properties?
i dont understand, what am i doing wrong?
thanks
Model is your ViewModel. Model.ScormModuleInfo is the IEnumerable of ScormModuleInfo type.
foreach (var module in Model.ScormModuleInfo)
In your controller you are passing ScormModuleViewModel to view not List<ScormModuleViewModel>
So Replace
System.Web.Mvc.ViewPage<List<Zinc.Web.Areas.Admin.ViewModels.Scorm.ScormModuleViewModel>>
To:
System.Web.Mvc.ViewPage<Zinc.Web.Areas.Admin.ViewModels.Scorm.ScormModuleViewModel>

MVC3 partial view with ViewModel property as model

I'm trying to pass a ViewModel property to a partial view, but getting the following error:
"The model item passed into the dictionary is of type '<>f__AnonymousType2`1[DomaniOnline.Models.DomaniData.TempRates]', but this dictionary requires a model item of type 'DomaniOnline.Models.DomaniData.TempRates'."
How do I pass the VM property so that it is not an anonymous type?
The View:
#model DomaniOnline.Models.ViewModels.CompareRatesViewModel
#{
ViewBag.Title = "Rate Comparison";
}
<h2>Compare Rates</h2>
<table>
<tr>
<td>#Html.DisplayTextFor(m=>m.TempRate1.CarrierName)</td>
<td>#Html.DisplayTextFor(m=>m.TempRate2.CarrierName)</td>
<td>#Html.DisplayTextFor(m=>m.TempRate3.CarrierName)</td>
<td>#Html.DisplayTextFor(m=>m.TempRate4.CarrierName)</td>
</tr>
<tr>
<td>#Html.Partial("_TempRatesPartial", new { tempRate = Model.TempRate1 })</td>
<td>#Html.Partial("_TempRatesPartial", new { tempRate = Model.TempRate2 })</td>
<td>#Html.Partial("_TempRatesPartial", new { tempRate = Model.TempRate3 })</td>
<td>#Html.Partial("_TempRatesPartial", new { tempRate = Model.TempRate4 })</td>
</tr>
</table>
The Partial View:
#model DomaniOnline.Models.DomaniData.TempRates
<fieldset>
<legend>TempRates</legend>
<div class="display-label">Carrier Name</div>
<div class="display-field">
#Html.DisplayFor(model => model.CarrierName)
</div>
....
</fieldset>
And the ViewModel:
public class CompareRatesViewModel
{
public TempRates TempRate1 { get; set; }
public TempRates TempRate2 { get; set; }
public TempRates TempRate3 { get; set; }
public TempRates TempRate4 { get; set; }
public TempRates TempRate5 { get; set; }
public CompareRatesViewModel(IEnumerable<TempRates> TempRateList)
{
this.TempRate1 = TempRateList[0];
this.TempRate2 = TempRateList[1];
this.TempRate3 = TempRateList[2];
this.TempRate4 = TempRateList[3];
this.TempRate5 = TempRateList[4];
}
}
Why not just pass in the object directly rather than using an anonymous type?
Your partial takes TempRates and your TempRate1 is of type TempRate so you should be able to do this without casting.
<td>#Html.Partial("_TempRatesPartial", Model.TempRate1)</td>
You need to cast your anonymous type as the type that is the model of your partial view:
#Html.Partial("_TempRatesPartial", (DomaniOnline.Models.DomaniData.TempRates)Model.TempRate1)

MVC3 Display a dropdown list from one datasource and save to another datasource

I'm getting back to an MVC3 project after a 3 month hiatus. I need to display a drop down list that pulls from Database A, but saves to Database B. The property I need to persist is the NAICS/SIC code. Right now I just provide the user a text box to key in freeform text. So, I have the mechanics of that down. But instead it should provide only a valid list of codes from a source database.
The tricky thing to is I'm using a custom model binder to generate my ViewModels on the fly, so I don't have a distinct .cshtml file to customize.
[Serializable]
public class Step4ViewModel : IStepViewModel
{
public Step4ViewModel()
{
}
//load naics codes from somewhere
[Display(Name = "Describe the nature of your business.")]
public String NatureOfBusiness { get; set; }
[Display(Name="NAICS/SIC CODE")]
public String BusinessTypeCode { get; set; }
Tricky ViewModel
#using Microsoft.Web.Mvc;
#using Tangible.Models;
#model Tangible.Models.WizardViewModel
#{
var currentStep = Model.Steps[Model.CurrentStepIndex];
var progress = ((Double)(Model.CurrentStepIndex) / Model.Steps.Count) * 100;
}
<script type="text/javascript">
$(function () {
$("#progressbar").progressbar({
value: #progress
});
});
</script>
<div id="progressbar" style="height:20px;">
<span style="position:absolute;line-height:1.2em; margin-left:10px;">Step #(Model.CurrentStepIndex + 1) out of #Model.Steps.Count</span>
</div>
#Html.ValidationSummary()
#using (Html.BeginForm())
{
#Html.Serialize("wizard", Model)
#Html.Hidden("StepType", Model.Steps[Model.CurrentStepIndex].GetType())
#Html.EditorFor(x => currentStep, null, "")
if (Model.CurrentStepIndex > 0)
{
<input type="submit" value="Previous" name="prev" />
}
if (Model.CurrentStepIndex < Model.Steps.Count - 1)
{
<input type="submit" value="Save & Continue" name="next" />
}
else
{
<input type="submit" value="Finish" name="finish" />
}
#*<input type="submit" value="Save" name="Save" />*#
}
Controller
[HttpPost]
public ActionResult Index([Deserialize] WizardViewModel wizard, IStepViewModel step)
{
wizard.Steps[wizard.CurrentStepIndex] = step;
if (ModelState.IsValid)
{
//Always save.
var obj = new dr405();
//wire up to domain model;
foreach (var s in wizard.Steps)
{
Mapper.Map(s,obj,s.GetType(), typeof(dr405));
}
using (var service = new DR405Service())
{
//Do something with a service here.
service.Save(db, obj);
}
if (!string.IsNullOrEmpty(Request["next"]))
{
wizard.CurrentStepIndex++;
}
else if (!string.IsNullOrEmpty(Request["prev"]))
{
wizard.CurrentStepIndex--;
}
else
{
return View("Upload", obj);
}
}
else if (!string.IsNullOrEmpty(Request["prev"]))
{
wizard.CurrentStepIndex--;
}
return View(wizard);
}
WizardViewModel
[Serializable]
public class WizardViewModel
{
public String AccountNumber { get; set; }
public int CurrentStepIndex { get; set; }
public Boolean IsInitialized { get { return _isInitialized; } }
public IList<IStepViewModel> Steps { get; set; }
private Boolean _isInitialized = false;
public void Initialize()
{
try
{
Steps = typeof(IStepViewModel)
.Assembly.GetTypes().Where(t => !t.IsAbstract && typeof(IStepViewModel).IsAssignableFrom(t)).Select(t => (IStepViewModel)Activator.CreateInstance(t)).ToList();
_isInitialized = true;
//rewrite this. get the profile and wire them up or something.
this.AccountNumber = Tangible.Profiles.DR405Profile.CurrentUser.TangiblePropertyId;
}
catch (Exception e)
{
_isInitialized = false;
}
}
}
You can specify a template for a specific property on your view model by adding the UIHint attribute to the field. Since your view calls EditorFor on the model it will use the template you specified with UIHint.
BusinessTypeDropdown.ascx - (placed in Views/Shared/EditorTemplates
<%# Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<string>" %>
<% var businessTypes = ViewData["businessTypes"] as IEnumerable<string>; %>
<%= Html.DropDownListFor(m => m , new SelectList(businessTypes, Model))%>
In your View Model
[Serializable]
public class Step4ViewModel : IStepViewModel
{
public Step4ViewModel()
{
}
//load naics codes from somewhere
[Display(Name = "Describe the nature of your business.")]
public String NatureOfBusiness { get; set; }
[Display(Name="NAICS/SIC CODE")][UIHint("BusinessTypeDropdown")]
public String BusinessTypeCode { get; set; }
Then in your controller just set ViewData["businessTypes"] to your list of business types.
Without understanding your "tricky" view model code, it will be hard to make helpful suggestions.
However, there shouldn't be much problem here. You need to somehow create your dropdown list in yoru view, and populate it from data passed from your controller.
All the work happens in your controller. Populate your list or IEnumerable or whatever data source from your first database, then in your post handler save the selection it to your second database (the second part should not be much different from what you already have).

Resources