Session or Cookies in login page = master page = child page - session

I' creating a multilanguage website and I have some files :
login page.
master page.
child page using master page.
In login page, I used link control for choose language by user :
<table class="borderlang" style="position: absolute; top: 5px; left: 5px; width: auto; height: auto;">
<tr>
<td style="vertical-align: middle;">
<asp:Label ID="Label1" runat="server" Text="Language :" meta:resourcekey="Label1Resource1"></asp:Label>
</td>
<td>
<a href="?lang=vi" runat="server" id="linkVietnameseLang">
<img src="Content/Images/VNlogo.jpg" style="height: 20px; width: auto; padding-left: 10px;" /></a>
</td>
<td>
<a href="?lang=en" runat="server" id="linkEnglishLang">
<img src="Content/Images/USALogo.png" style="height: 20px; width: auto; padding-left: 10px;" /></a>
</td>
</tr>
</table>
I use BasePage.cs with code :
public class BasePage : System.Web.UI.Page
{
protected override void InitializeCulture()
{
if (!string.IsNullOrEmpty(Request["lang"]))
{
Session["lang"] = Request["lang"];
}
string lang = Convert.ToString(Session["lang"]);
string culture = string.Empty;
if (lang.ToLower().CompareTo("en") == 0)
{
culture = "en-US";
}
if (lang.ToLower().CompareTo("vi") == 0 || string.IsNullOrEmpty(culture))
{
culture = "vi-VN";
}
Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(culture);
Thread.CurrentThread.CurrentUICulture = new CultureInfo(culture);
base.InitializeCulture();
}
}
So in login page I use :
public partial class Login : BasePage
To use BasePage.
In this form have some items that I can't use local resource, so I used 2 resources : global resource and local resource. But I don't care because when I choose language in link -> language change and global and local resource are changed, too.
Now, when I login, website will redirect to a page using master page. In master page I put a dropdown for user in case they wanna change language again :
<asp:DropDownList ID="ddlLanguage" runat="server"
OnSelectedIndexChanged="ddlLanguage_SelectedIndexChanged"
AutoPostBack="True" meta:resourcekey="ddlLanguageResource1">
<asp:ListItem Text="Tiếng ViệT" Value="vi-VN" meta:resourcekey="ListItemResource1" />
<asp:ListItem Text="EnglisH" Value="en-US" meta:resourcekey="ListItemResource2" />
</asp:DropDownList>
And in master page I add :
if (!Page.IsPostBack)
{
ddlLanguage.SelectedValue = Thread.CurrentThread.CurrentCulture.Name;
}
and :
protected void ddlLanguage_SelectedIndexChanged(object sender, EventArgs e)
{
//Sets the cookie that is to be used by Global.asax
HttpCookie cookie = new HttpCookie("CultureInfo");
cookie.Value = ddlLanguage.SelectedValue;
Response.Cookies.Add(cookie);
//Set the culture and reload the page for immediate effect.
//Future effects are handled by Global.asax
Thread.CurrentThread.CurrentCulture =
new CultureInfo(ddlLanguage.SelectedValue);
Thread.CurrentThread.CurrentUICulture =
new CultureInfo(ddlLanguage.SelectedValue);
Server.Transfer(Request.Path);
}
In global.asax is :
protected void Application_BeginRequest(object sender, EventArgs e)
{
HttpCookie cookie = Request.Cookies["CultureInfo"];
if (cookie != null && cookie.Value != null)
{
Thread.CurrentThread.CurrentUICulture = new CultureInfo(cookie.Value);
Thread.CurrentThread.CurrentCulture = new CultureInfo(cookie.Value);
}
else
{
Thread.CurrentThread.CurrentUICulture = new CultureInfo("vi-VN");
Thread.CurrentThread.CurrentCulture = new CultureInfo("vi-VN");
}
}
Question 1 : How can I use session or cookies of link value (in login page) to master page : ddlanguage value = session or cookies of lang ??
Now, in child page using master page. I must use local resource because if use global resource I must use <%$ Resources:nameresource, keysource%> -> too slow.
And I have a problem : in child page with local resoure, culture and uiculture value is not depending on ddlanguage value in master page.
Question 2 : How can I set culture and uiculture value in child page = ddlanguage value in master page.
And result is : lang value in login page = ddlanguage dropdown value in master page = culture and uiculture in child page using that masterpage. But can change ddlanguage value in masterpage and cultureanduiculture in child page will change, too.
.
I'm an amateur in coding, so I hope have solution in my case.
Thank very very much (and sorry for my English).

In program.cs
user name can set Globals variable
namespace GlobalVariables
{
public static class Globals
{
static Globals()
{
userName="";
}
public static void setusername(int[] newInt)
{
setusername = newInt;
}
public static string userName { get; private set; }
}
you can set or get every child or parent form
inherit namespace like in another child or parent form
using GlobalVariables;
to set Globals session or cookiee
Globals.setusername(userName.ToString()));
you can check and restrict page
username=Globals.userName;
Response.Cookies("userInfo")("userName") = "rangarajakrishnan"
Response.Cookies("userInfo")("lastVisit") = DateTime.Now.ToString
Response.Cookies("userInfo").Expires = DateTime.Now.AddDays(1)
Dim aCookie As New HttpCookie("userInfo")
aCookie.Values("userName") = "mike"
aCookie.Values("lastVisit") = DateTime.Now.ToString
aCookie.Expires = DateTime.Now.AddDays(1)
Response.Cookies.Add(aCookie)

Related

_layout.cshtml not seeing object when at /Home/Index

I am writing an ASP.NET Core 6 MVC app.
I have an object of type UserInfo that is set (not important where).
Under Shared, my _Layout.cshtml shows the "Login ID" at the top in a menu bar.
The portion that shows this user name is in a _LogInOutPartial.cshtml
in the the partial view, I inspect the UserInfo object and set a variable displayUser accordingly: if the user object is null, I set the variable to "Guest", otherwise I pull the login id into this variable.
Code in _LogInOutPartial.cshtml is:
#model SisExtMvcAppSSO.Models.UserInfo;
#{
bool isGuest = (Model == null || !Model.IsLogged);
bool isLoggedIn = !isGuest;
string displayUser = (isGuest ? "Guest" : Model.LoginId);
}
<button class="btn btn-outline-success my-2 my-sm-0">
<i class="bi bi-person-badge"></i> #displayUser
</button>
When the object is set, if I go to some controller/action, e.g. https://some.com/myApp/Home/Claims, the login id shows fine (e.g. "mcollins") in the top menu bar.
However, if I go to https://some.com/myApp/ (or https://some.com/myApp/Home/Index or https://some.com/myApp/Home), the menu bar (_layout.cshtml) will not show the login id, instead it shows "Guest"
This is even when the /Home/Index will show the login id in its view!
The problem is, apparently, the object it is not seen in _Layout.cshtml.
But then how come it is seen in the menu bar (_Layout.cshtml) when I go to /Home/Claims?
Usually,we will use UserManager as the model in _LogInOutPartial.cshtml for Identity.If you don't want to use it,you can try to use Session and add the object to session in somewhere.Once the data is added,you can get it in other views.
Program.cs:
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllersWithViews();
builder.Services.AddDistributedMemoryCache();
builder.Services.AddSession(options =>
{
options.IdleTimeout = TimeSpan.FromDays(1);
options.Cookie.HttpOnly = true;
options.Cookie.IsEssential = true;
});
...
app.UseAuthorization();
app.UseSession();
...
partial view:
#using Microsoft.AspNetCore.Http;
#using Newtonsoft.Json;
#{
UserInfo userInfo=null;
if (!string.IsNullOrEmpty(Context.Session.GetString("userInfo")))
{
userInfo = JsonConvert.DeserializeObject<UserInfo>(Context.Session.GetString("userInfo"));
}
bool isGuest = (userInfo == null || !userInfo.IsLogged);
bool isLoggedIn = !isGuest;
string displayUser = (isGuest ? "Guest" : userInfo.LoginId);
}
<button class="btn btn-outline-success my-2 my-sm-0">
<i class="bi bi-person-badge"></i> #displayUser
</button>
Action:
public IActionResult YourAction()
{
UserInfo userInfo = new UserInfo { LoginId = "mcollins", IsLogged = true };
HttpContext.Session.SetString("userInfo", JsonConvert.SerializeObject(userInfo));
return View();
}

Apex:outputfield not outputting anything on VisualForce Page

I am trying to create a pdf from the Lead Object in Salesforce using the Apex language. I am able to create the pdf and attach it to the Current Lead but it does not pull in any of the information from the Lead into the PDF itself.
Page Code:
<apex:page standardController="Lead" renderAs="pdf" showHeader="false">
<apex:stylesheet value="{!$Resource.pdfCss}"/>
<apex:panelGrid columns="1" width="100%">
<apex:outputText value="{!Lead.Name}" styleClass="companyName"/>
<apex:outputText value="{!NOW()}"></apex:outputText>
</apex:panelGrid>
</apex:page>
Class Code:
public class attachPDFToLead {
private final Lead a; //Lead object
//constructor
public attachPDFToLead(ApexPages.StandardController standardPageController) {
a = (Lead)standardPageController.getRecord();
}
public PageReference attachPDF() {
PageReference pdfPage = Page.PDF;
Blob pdfBlob = pdfPage.getContent();
Attachment attach = new Attachment(parentId = a.Id, Name = 'insuranceVerification.pdf', body = pdfBlob);
insert attach;
PageReference pageURL = new ApexPages.StandardController(a).view();
pageURL.setRedirect(true);
return pageURL;
}
}
Button Setup:
Button Setup

Updating only the partial view contained in a mvc 3 page?

I have a MVC 3 page that returns a list of user responses with a partial view called "memo" (which displays/add memos) for each response. When I add a memo to a response, it should update the db and the list of memos for that response. It should be partial page update via ajax, which effects only the partial view "memo".
The view Response.chtml that contains "memo":
#using (Html.BeginForm("Response", "User", FormMethod.Post, new { id = "UserResponse" }))
{
.... code removed ....
#foreach (var response in Model)
{
<div class="qna"><input type="text" id=#response.responseId value="#response.ResponseText" />
<div>#Html.Partial("_memo", response.responseId)</div>
}
.....
The partial page "_memo.chtml":
<div>add memo</div>
<ul id="memos">
#foreach (var memo in Model) {
<li>#memo.Text</li>
}
</ul>
<form method="post" id="memoForm"
action="#Url.Action("AddMemo")">
#Html.TextArea("Memo", new { rows = 5, cols = 50 })
<br />
<input type="submit" value="Add" />
</form>
Controller for view User/Response:
[HttpGet]
public ActionResult Response(id)
{
.....
return View(responses);
I just started with the code above, need help filling the blanks.
If I pass the response Id to the partial view, how do I pull the list of memos for that response? Will it involve ajax? (instead of ..Partial("_memo", response.memos))
How do I update the partial view via ajax call. What is ajax call (sample code) on the client side and how would the controller look? When the ajax call is successful, how do I update the list memos div="memos" to reflect the new memo?
Will the form action from Response conflict with form action of the partial view Memo?
Answers to Questions:
You shouldn't pass the responseId to the partial, you should pass the memo collection from your response object and make your partial view strongly typed to that collection.
See full code example below.
You don't need the form in the partial since you're making a simple ajax call to add the new memo. See full code example below.
This is a modified example from a project I am currently working on:
There is a bit of code to follow, so here goes:
This is my model. There are several sections on a career planning form, one of which is a section to select and update competencies. The SelectCompetencies model has a collection of competencies within it. The user will have the ability to add competencies. When they do, it will be added to the database and will update the list of competencies in the partial.
public class CareerPlanningFormViewModel
{
// code removed ...
public SelectCompetenciesModel SelectCompetencies { get; set; }
// code removed ...
}
public class SelectCompetenciesModel
{
public int CareerPlanningFormID { get; set; }
public IList<CompetencyModel> Competencies { get; set; }
public byte MaximumCompetenciesAllowed { get; set; }
}
public class CompetencyModel
{
public int CompetencyID { get; set; }
public int? CompetencyOptionID { get; set; }
public string ActionPlan { get; set; }
public IDictionary<int, string> CompetencyOptions { get; set; }
}
The main view of the career planning form: /Views/CPF/CareerPlanningForm.cshtml
#model MyNamespace.Models.CareerPlanningForm.CareerPlanningFormViewModel
<link rel="stylesheet" href="#Url.Content("~/Content/CreateCPF.css")" />
#using (Html.BeginForm())
{
// other sections loaded here...
// code removed for brevity...
#Html.Partial("SelectCompetencies", Model.SelectCompetencies)
// other sections loaded here...
// code removed for brevity...
}
The SelectCompetencies partial: /Views/CPF/SelectCompetencies.cshtml
The user will fill in the new action plan text and click the add competency button.
That will post via ajax to CPFController/NewCompetencyTemplate
#model MyNamespace.Models.CareerPlanningForm.SelectCompetenciesModel
#Html.HiddenFor(m => m.CareerPlanningFormID)
<h3>Select Competencies</h3>
<p class="guidance">
Select up to #Model.MaximumCompetenciesAllowed competencies to focus on improving.
</p>
<table id="CompetenciesTable">
<thead>
<tr>
<th>Competency</th>
<th>Action Plan:</th>
</tr>
</thead>
<tbody>
#for (int i = 0; i < Model.Competencies.Count(); i++)
{
#Html.EditorFor(m => m.Competencies[i])
}
</tbody>
<tfoot id="CompetenciesTableFooter" class="#(Model.Competencies.Count() < Model.MaximumCompetenciesAllowed ? "" : "hidden")">
<tr>
<td colspan="2">
#Html.TextArea("NewActionPlanText")
#Html.Button(ButtonType.Button, "Add Another Competency", "add", new { id = "AddCompetencyButton" })
</td>
</tr>
</tfoot>
</table>
#section script
{
<script>
jQuery(document).ready(function ($) {
var competenciesTableBody = $('#CompetenciesTable tbody'),
competenciesTableFooter = $('#CompetenciesTableFooter'),
addCompetencyButton = $('#AddCompetencyButton'),
newCompetencyTemplateUrl = '#Url.Content("~/CPF/NewCompetencyTemplate")',
count = competenciesTableBody.find('tr').length,
newActionPlanText = $('#NewActionPlanText'),
careerPlanningFormID = $('#CareerPlanningFormID');
addCompetencyButton.click(function () {
$.ajax({
url: newCompetencyTemplateUrl(),
type: 'POST',
data: {
careerPlanningFormID: careerPlanningFormID,
actionPlan: newActionPlanText,
itemCount: count
},
dataType: 'html',
success: function (data) {
var elements = $(data);
// other code removed here...
competenciesTableBody.append(elements);
// other code removed here...
}
});
});
});
</script>
}
Views/CPF/EditorTemplates/CompetencyModel.cshtml
#model MyNamespace.Models.CareerPlanningForm.CompetencyModel
<tr class="competency">
<td>
#Html.DropDownListFor(m => m.CompetencyOptionID, new SelectList(Model.CompetencyOptions, "Key", "Value"), "Select competency...")
</td>
<td>
#Html.TextAreaFor(m => m.ActionPlan, new { #class = "competencyActionPlan" })
#Html.HiddenFor(m => m.CompetencyID)
</td>
</tr>
The controller containing the action to add the new competency: /Controllers/CPFController.cs
This will call the CareerPlanningFormService to add the new competency and will return a partial view for NewCompetencyTemplate that will render out the new competency
public class CPFController : Controller
{
private readonly ICareerPlanningFormService careerPlanningFormService;
public CPFController(ICareerPlanningFormService careerPlanningFormService)
{
this.careerPlanningFormService = careerPlanningFormService;
}
[HttpPost]
public PartialViewResult NewCompetencyTemplate(int careerPlanningFormID, int itemCount, string newActionPlanText)
{
var count = itemCount + 1;
// Even though we're only rendering a single item template, we use a list
// to trick MVC into generating fields with correctly indexed name attributes
// i.e. Competencies[1].ActionPlan
var model = new SelectCompetenciesModel
{
Competencies = Enumerable.Repeat<CompetencyModel>(null, count).ToList()
};
model.Competencies[count - 1] = this.careerPlanningFormService.BuildNewCompetencyModel(careerPlanningFormID, newActionPlanText);
return this.PartialView(model);
}
}
My service class: CareerPlanningFormService.cs
This handles the business logic and makes the calls to the repository to add the item to the database and returns a new CompetencyModel
public class CareerPlanningFormService : ICareerPlanningFormService
{
private readonly IMyRenamedRepository repository;
private readonly IPrincipal currentUser;
public CareerPlanningFormService(
IMyRenamedRepository repository,
IPrincipal currentUser)
{
this.repository = repository;
this.currentUser = currentUser;
}
public CompetencyModel BuildNewCompetencyModel(int careerPlanningFormID, string newActionPlanText)
{
var competency = new Competency
{
CareerPlanningFormID = careerPlanningFormID,
CompetencyOptionID = null,
ActionPlan = newActionPlanText
};
this.repository.Add(competency);
this.repository.Commit();
return new CompetencyModel
{
CompetencyID = competency.CompetencyID,
CompetencyOptionID = competency.CompetencyOptionID,
ActionPlan = competency.ActionPlan,
CompetencyOptions = this.GetCompetencyOptionsForCareerPlanningFormID(careerPlanningFormID)
};
}
}
Now, the partial for NewCompetencyTemplate: Views/CPF/NewCompetencyTemplate.cshtml
This is very simple, it simply renders the same editor template as above, for the last competency in the collection (which we just added)
#model MyNamespace.Models.CareerPlanningForm.SelectCompetenciesViewModel
#Html.EditorFor(m => m.Competencies[Model.Competencies.Count() - 1])
When the ajax call succeeds, it will receive this partial back from the controller action method it called. It then takes the partial and appends it to the competencies table body
// snippet from ajax call above
competenciesTableBody.append(elements);
I hope this helps. Let me know if you have any additional questions.
While you're correct that you can do it just by returning a partial view containing the updated content, you may also consider using jQuery's load method.
Look here, in particular at the "loading page fragments" section. Basically you can just get the original page again and jQuery will "extract" the content you want as long as it can be targetted by a selector (such as a div id).
Note, this solution is not suitable in all cases as there will be redundant markup in the response from the server because you will be discarding the rest of the page content and just using the updated part.

ASP.NET MVC 3 WITH RAZOR : How to pass selected checkbox' ids in a Partial view to controller action?

I have a partialview [_SearchProduct] within the main view, let's say [product] view. The Partialview has a number of checkboxes segregated into different sections like search by company,search by product etc. with one [search] button.
A User can select multiple checkboxes. When user clicks [search] button I need to pass ids of all selected checkbox to controller action and re-render the page again considering the user's selection . Please guide me how to pass selected checkbox ids to my controller action.
My partial view is something like below:
<fieldset>
<legend>By Company</legend>
<table style="border-style: none;">
<tr>
#{
int i = 0;
foreach (var item in Model.CompanyName)
{
i = i + 1;
<td style="border-style: none;text-decoration:none;" >
#Html.CheckBox("chkCompany",new {id="chkCompany_" + Model.CompanyId.Tostring()}) #Model.CompanyName
</td>
if (i == 5)
{
#:</tr><tr>
i = 0;
}
}
}
</tr>
</table>
</fieldset>
<fieldset>
<legend>By Product</legend>
<table style="border-style: none;">
<tr>
#{
i = 0;
foreach (var item in Model.Product)
{
i = i + 1;
<td style="border-style: none;text-decoration:none;" >
#Html.CheckBox("chkProduct",new {id="chkProduct_" + Model.CompanyId.Tostring()}) #Model.ProductName
</td>
if (i == 10)
{
#:</tr><tr>
i = 0;
}
}
}
</tr>
</table>
</fieldset>
checkboxes are dynamic
Checkbox id represent the primarykey of respective table based on which i do filtering.
Please guide me>>
So it sounds like you have a structure containing names (of companies/products), and ids.
I would create a View Model structure that looked like
public class PartialViewModel //Make sure this is included in your main view model
{
public List<ObjectsToInclude> Companies { get; set; }
public List<ObjectsToInclude> Products { get; set; }
}
public class ObjectsToInclude //Give this a better name
{
public string Name { get; set; }
public string Id { get; set; }
public bool Include { get; set; }
}
Then in order to bind them you could do
for (int i =0; i<Model.Companies.Count(); i++)
{
<td style="border-style: none;text-decoration:none;" >
#Html.HiddenFor(m => m.Companies[i].Id)
#Html.CheckBoxFor(m => m.Companies[i].Include) #Model.Companies[i].Name
</td>
if (i == 5)
{
#:</tr><tr>
i = 0;
}
}
Then provided your post takes a parameter of PartialViewModel (or some MainViewModel where that contains an instance of PartialViewModel), you'll have lists of companies and products binded. You can loop through the list, and take the respective ids of anything checked to be included.
Edit: If you wanted a single comma separated array to be posted, it would be possible by by creating an onclick event for your checkboxes, and then setting a value of a hidden input every time a checkbox is clicked. But then your code would only work with JavaScript enabled. If you need a comma separated string, you can create it server side with the view model I suggested.
string companyIds = String.Join(",", model.Companies
.Where(company => company.Include)
.Select(company => company.Id));
http://dotnetnsqlcorner.blogspot.in/2012/09/multiple-checkboxes-in-mvc-3-and-post.html

Mvc 3 Image Upload Gallery

I have implemented a file upload for images using ASP.NET Mvc 3 and the Microsoft.Web.Helpers NuGet package. The implementation is quit simple as it allows you to browse for a file and upload it to a specified directory.
Here is what I have for my image upload solution using ASP.NET MVC 3 and the Microsoft.Web.Helpers NuGet plugin.
Now the ViewModel code
namespace MvcImageUpload.Models {
public class ImageUploadViewModel {
[UIHint("UploadedImage")]
public string ImageUrl { get; set; }
public string ImageAltText { get; set; }
}
}
Now for the controller I've simply dropped this into the Home controller, since this is just a mock project to get it working. I just added an ActionResult which takes an ImageUploadViewModel as a parameter.
public ActionResult Upload(ImageUploadViewModel model) {
var image = WebImage.GetImageFromRequest();
if (image != null) {
if (image.Width > 500) {
image.Resize(500, ((500 * image.Height) / image.Width));
}
var filename = Path.GetFileName(image.FileName);
image.Save(Path.Combine("../Uploads/Images", filename));
filename = Path.Combine("~/Uploads/Images", filename);
model.ImageUrl = Url.Content(filename);
model.ImageAltText = image.FileName.Substring(0, image.FileName.Length - 4);
}
return View("Index", model);
}
My view for the uploading of images is simple, it has an Html.BeginForm, which handles the Post form method and has the encoding type set to be "multipart/form-data".
Then using The Microsoft.Web.Helpers.FileUpload helper, I request an image from the HTTP post and then display it using a custom DisplayFor template, called ImageViewer.
#model MvcImageUpload.Models.ImageUploadViewModel
#using Microsoft.Web.Helpers;
#{
ViewBag.Title = "Index";
}
<h2>Image Uploader</h2>
#using (Html.BeginForm("Upload", "Home", FormMethod.Post,
new { #encType = "multipart/form-data" })) {
#FileUpload.GetHtml(initialNumberOfFiles: 1, allowMoreFilesToBeAdded: false,
includeFormTag: false, addText: "Add Files", uploadText: "Upload File") <br />
<input type="submit" name="submit"
value="Upload Image" text="Upload Images"
style="font-size: .9em;" />
#Html.DisplayFor(x => x, "ImageViewer")<br />
}
Here is what the custom DisplayTemplate looks like
#model MvcImageUpload.Models.ImageUploadViewModel
#if (Model != null) {
<h4 style="color:Green;">Upload Success!</h4>
<p>
Alt Text has been set to <strong>#Model.ImageAltText</strong>
</p>
<img style="padding: 20px;"
src="#(String.IsNullOrEmpty(Model.ImageUrl) ? "" : Model.ImageUrl)"
id="uploadedImage" alt="#Model.ImageAltText"/>
}
This all works and the image gets successfully uploaded to the /Uploads/Images/FileName.extension on the form post.
My question
How can I now have another view to display all the images in that directory, paged and be able to select and delete and image, from the view and the directory?
Also I know the Microsoft.Web.Helpers.FileUpload, supports uploading of multiple files, but I can't find how to implement this with my current solution. Any help would be greatly appriceated.
After you click the Upload Image button, the system should call method which uses Request to get the file.
[HttpPost]
public ActionResult Upload()
{
if(Request.Files != null && Request.Files.Count > 0)
{
for (int i = 0; i < request.Files.Count; i++)
{
var postFile = request.Files[i];
if (postFile != null && postFile.ContentLength > 0)
{
if (postFile.ContentLength < GetMaxRequestLength()) //10MB
{
var file = new ContractAttachment
{
Name = Path.GetFileName(postFile.FileName),
ContentType = postFile.ContentType,
FileLength = postFile.ContentLength,
FileData = GetStreamBuffer(postFile)
};
files.Add(file);
}
}
}
}
}
Hope this help.
what you are asking about looks rather implementation to me then any query....
to Display:
Fetch all images from your Uploads/Images directory through DirectoryInfo... you can search a directory based on some extension and then it will give you a result set which you can iterate.....
Create a view that will display all records as Image links and in controller fetch the resultset to that View.... Bind those records as you want them to display in your VIEW...
System.IO.DirectoryInfo info = new System.IO.DirectoryInfo("your directory path");
var filesinfo= info.GetFiles("*.jpg", System.IO.SearchOption.AllDirectories);
var filenum= filesinfo.GetEnumerator();
while (filenum.MoveNext())
{
//populate some entity like in your case you have ImageUploadViewModel
}
and you can implement you delete logic using Ajax or through post back depends how you want it....
Asp.net MVC Views following this tutorial and it will let you go through this....
but again what you are asking is more like implementation Code not any issue....
The approach I've followed previously, is to persist the file information in a database(or whatever is appropriate). e.g. path, filename, content-type, filesize.
This gives you the most flexibility when editing (alt text, title, description, relation to other objects).
Downloading/Viewing the files can then be handled based on path convention, by creating a ViewImage controller which just gets an image id as parameter.
You can then build a url from the path to the file and you only need to set the content-type.
IIS then does the rest.

Resources