Model is null when url.action is called in asp.net - c#

My model have List products which get from database.
When index view loaded, i get the variable from input of user, then model get varible, and return view OutputTableAsync. After view loaded, i click link "Export Excel", in debug mode, List products is null.
My view:
<body>
#if (Model != null)
{
var products = Model.products.Products;
Export Excel
<table border="1" style="width: 100%">
<thead>
<tr>
<th>Model</th>
<th>Price</th>
<th>Link</th>
<th>ImageUrl</th>
</tr>
</thead>
<tbody>
#foreach (var product in Model.products.SortProduct())
{
<tr id="i">
<td align="center">#product.Model</td>
<td align="center">#product.FormatPrice()</td>
<td align="center">#product.Link</td>
<td align="center"><img src="#product.ImageUrl" style="width : 200px; height:200px ;" id="#product.ImageUrl" /></td>
</tr>
}
</tbody>
</table>
}
</body>
ExportToExcel method in controller:
public void ExportToExcel(List<Product> products)
{
ExcelPackage pck = new ExcelPackage();
ExcelWorksheet ws = pck.Workbook.Worksheets.Add("Products");
ws.Cells["A1"].Value = "Model";
ws.Cells["B1"].Value = "Price";
ws.Cells["C1"].Value = "Link";
ws.Cells["D1"].Value = "ImageLink";
int rowstart = 2;
foreach(var item in products)
{
ws.Cells[string.Format("A{0}", rowstart)].Value = item.Model;
ws.Cells[string.Format("B{0}", rowstart)].Value = item.Price;
ws.Cells[string.Format("C{0}", rowstart)].Value = item.Link;
ws.Cells[string.Format("D{0}", rowstart)].Value = item.ImageUrl;
rowstart++;
}
ws.Cells["A:AZ"].AutoFitColumns();
Response.Clear();
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader("content-disposition", "attachment: filename=" + "ExcelFile.xlsx");
Response.BinaryWrite(pck.GetAsByteArray());
Response.End();
}

According to accepted answer here you can not pass complex type through Url.Action
I would pass serialized version of object in this situation.

Related

how to find point in line and then after add a content in new line

now my content is a one line but I want to new content is new line after the point(.)
.cs
[HttpGet]
public async Task<ActionResult> Career()
{
HttpClient client = new HttpClient();
HttpResponseMessage responseMessage = client.GetAsync("https://localhost:0000/Home/DisplayVacancyData").Result;
if (responseMessage.IsSuccessStatusCode)
{
//data = await responseMessage.Content.ReadAsAsync();
//List<Vacancy> products = await responseMessage.Content.ReadAsAsync<List<Vacancy>>();
string result = await responseMessage.Content.ReadAsStringAsync();
List<Vacancy> vaca = JsonConvert.DeserializeObject<List<Vacancy>>(result);
ViewBag.message = vaca + "<br />";
return View("Career",vaca);
}
return View();
}
.cshtml
<table class="table table-striped border">
<thead>
<tr>
<th>Vacancy Title</th>
<th>Vacancy Position</th>
<th>Vacancy Experience</th>
<th>Vacancy Jobdescription</th>
<th>Vacancy RequiredSkil</th>
<th>Action</th>
</tr>
</thead>
<tbody>
#foreach (var carr in Model)
{
//string newline = "\n";
<tr>
<td>#carr.vacancytitle</td>
<td>#carr.vacancyposition</td>
<td>#carr.vacancyexperience</td>
#*if()*#
<td>#carr.vacancyjobdescription#*<text> & nbsp;</ text >*#</td>
<td>#carr.vacancyrequiredskill</td>
<td>
#Html.ActionLink("Apply for Job", "ApplyForJob")
</td>
</tr>
}
</tbody>
</table>
means after point new content in separate line
logic is first find the point(.) in line then after add a new line
string newline = "\n";
if(carr.vacancyjobdescription)
{
//issue is here how to find out point in line
and then add a <text>newline</text>
}
what I am trying - main issue is how to find the point
<td>
#if (carr.vacancyjobdescription != null)
{
#carr.vacancyjobdescription
<text> </text>
}
</td>
<td>
#{
string skillHtml = #carr.vacancyrequiredskill;
skillHtml = skillHtml.Replace(".", "</br>");
}
#*Here we gonna display the html*#
#Html.Raw(skillHtml)
</td>
#{string data = "Hello. This is Test. Yo";
data= data.Replace(".", "</br>");}
#*Then to display your value use...*#
#Html.Raw(data)

why is file.PostedFile is always null

I need to upload images to my data base, and in order to that I need to bring them to the server side.
The only problem is the file is always null and I can't use it.
html:
<form id="signUpForm" runat="server" action="signUp.aspx" method = "get" name = "signUp"
enctype="multipart/form-data" onsubmit = "return validateSignUp();">
<div id = "input">
<table>
<tr>
<td class = "description">*profile image: </td>
<td class = "input" id = "inputProfileImage"><input type = "file" name = "profileImage" accept = "image/png, image/jpeg, image/jpg" id = "profileImage" runat="server"/>
<div class = "warning" id = "warnProfileImage"></div>
</td>
</tr>
<tr>
<td><input type = "submit" value = "sign up"/></td>
<td><input type = "reset" value = "reset"/></td>
</tr>
</table>
</div>
<div id = "showInfo">
<table>
<tr><td class = "description">profile image:</td><td class = "input"><img src = "defaultProfileImages/defaultProfileImage1.png" id = "showProfileImage" name="showProfileImage" runat="server"/></td></tr>
<tr><td><input type = "submit" name = "submit" value = "confirm"/></td></tr>
</table>
</div>
</form>
c#:
if (Request.QueryString["submit"] != null)
{
string path = "";
if ((profileImage.PostedFile != null) && (profileImage.PostedFile.ContentLength > 0))
{
string fn = System.IO.Path.GetFileName(profileImage.PostedFile.FileName);
string SaveLocation = Server.MapPath("Temp") + "\\" + fn;
path = SaveLocation;
try
{
profileImage.PostedFile.SaveAs(SaveLocation);
Response.Write("The file has been uploaded.");
}
catch (Exception ex)
{
Response.Write("Error: " + ex.Message);
//Note: Exception.Message returns a detailed message that describes the current exception.
//For security reasons, we do not recommend that you return Exception.Message to end users in
//production environments. It would be better to put a generic error message.
}
}
User user = new User(Libary.convertFile(path));
UserService userService = new UserService();
userService.InsertUser(user);
Response.Redirect("homePage.aspx");
Response.End();
}
*I deleted all the lines that doesn't has anything to do with the file.
Try to use HttpPostedFileBase instead of PostedFile for quick issue resolve.
Turn out you can't get a file in the server side if you are using a "get" method in your form. So you just need to change the form method to "post".
HTML:
<form id="signUpForm" runat="server" action="signUp.aspx" method = "post" name = "signUp" enctype="multipart/form-data" onsubmit = "return validateSignUp();">
<table>
<tr>
<td class = "description">phone number: </td>
<td class = "input" id = "inputPhoneNumber"><input type = "tel" pattern="[0-9]{3}-[0-9]{7}" name = "phoneNumber" id = "phoneNumber" runat="server"/><div class = "warning" id = "warnPhoneNumber"></div></td>
</tr>
<tr>
<td class = "description">*profile image: </td>
<td class = "input" id = "inputProfileImage"><input type = "file" name = "profileImage" accept = "image/png, image/jpeg, image/jpg" id = "profileImage" runat="server"/>
<div class = "warning" id = "warnProfileImage"></div>
</td>
</tr>
<tr>
<td><input type = "submit" value = "sign up"/></td>
<td><input type = "reset" value = "reset"/></td>
</tr>
</table>
</form>
You just need to know that you can't use "Request" if your from method is "post", So I just used one of the others input's in the form.
C#:
using System.Drawing;
using System.IO;
public partial class signUp : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if ((phoneNumber.Value != null) && (phoneNumber.Value.Length > 0))
{
string path = "";
bool deleteFile = false;
if ((profileImage.PostedFile != null) && (profileImage.PostedFile.ContentLength > 0))
{
path = Libary.save(profileImage.PostedFile, Server);
deleteFile = true;
}
User user = new User(Libary.convertFile(path));
UserService userService = new UserService();
userService.InsertUser(user);
Response.Redirect("homePage.aspx");
Response.End();
if ((deleteFile) && (File.Exists(path))){File.Delete(path);}
}
}
}
*Libary.save(HttpPostedFile file, HttpServerUtility Server) function is just saving the file and returning the path to it.

How to display the list using viewdata[" "] in the view?

I have to display my details in the list view .I am storing my details in controller using viewdata and i need to use the viewdata in my view .The view part is not working.IN view part i have to use view data inside foreach and iterate through the list .Help me out!!
Previously i was storing in static list given below:
public static List<EmployeeModel> staticEmployeeViewModelList = new List<EmployeeModel>();
my controller part
public async Task<IActionResult> ImportEmployeeDetails(IFormFile excelfile)
{
try
{
EmployeesViewModelList employeesListObject = new EmployeesViewModelList();
// var employeesListObject = new EmployeesViewModelList();
List<EmployeeModel> employeesViewModelList = new List<EmployeeModel>();
if (excelfile == null || excelfile.Length == 0)
{
return View(employeesListObject);
}
var supportedTypes = new[] { ".xls", ".xlsx" };
var ext = Path.GetExtension(excelfile.FileName);
if (!supportedTypes.Contains(ext))
{
return View(employeesListObject);
}
var path = Path.Combine(
Directory.GetCurrentDirectory(), "wwwroot",
"EmployeeDetails.xlsx");
FileInfo file = new FileInfo(path);
using (ExcelPackage package = new ExcelPackage(file))
{
ExcelWorksheet worksheet = package.Workbook.Worksheets[1];
int rowCount = worksheet.Dimension.Rows;
int ColCount = worksheet.Dimension.Columns;
for (int i = 2; i <= rowCount; i++)
{
EmployeeModel emp = new EmployeeModel();
// emp.EmployeeId = Convert.ToInt32(worksheet.Cells[i, 1].Value.ToString());
emp.EmpEin = worksheet.Cells[i, 1].Value.ToString();
emp.EmpFirstName = worksheet.Cells[i, 2].Value.ToString();
employeesViewModelList.Add(emp);
}
ViewData["EmployeeList"] = employeesViewModelList;
//to get data
employeesViewModelList = ViewData["EmployeeList"] as List<EmployeeModel>;//convert back to llist
staticEmployeeViewModelList = employeesViewModelList.ToList();
ViewData["EmployeeList"] = employeesViewModelList.ToList();
employeesListObject.EmpModelList = employeesViewModelList;
employeesViewModelList = ViewData["EmployeeList"] as List<EmployeeModel>;
// return View(employeesListObject);
return View(employeesListObject);
}
}
catch(Exception ex)
{
ViewData["Message"] = "Opps! Something Went wrong!";
return RedirectToAction("ExcelPackage");
}
}
My View:
My view
// In foreach loop i have used the below code
#foreach (var employee in (List)TempData["EmployeeList"])
{
#foreach(var item in employee.EmpModelList.ToList())
{
// the above one is not working
--------------------------------------------------------------------------
Save
EmpEin
FirstName
LastName
Email
Country
<th></th>
</tr>
</thead>
<tbody>
#foreach (var item in Model.EmpModelList.ToList())
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.EmpEin)
</td>
<td>
#Html.DisplayFor(modelItem => item.EmpFirstName)
</td>
<td>
#Html.DisplayFor(modelItem => item.EmpLastName)
</td>
<td>
#Html.DisplayFor(modelItem => item.EmpEmail)
</td>
<td>
#Html.DisplayFor(modelItem => item.HomeCountry)
</td>
<td>
<td><a class="edit" href="javascript:;">Edit</a></td>
<td class="EmpId" style="display:none">#Html.DisplayFor(modelItem => item.EmpEin)</td>
</td>
</tr>
}
</tbody>
</table>
</div>
}
In order to use ViewData in view ,first we have to store the list of properties in controller using an object .As we need to bind the model class in the view to get the list properties and we have to use the model directly in view .
#using ECOLAB.SIP.Web.XXXXXX #*(model folder)*#
#model ECOLAB.SIP.Web.Models.XXXXXXX #*(class name inside the model folder)*#
after that we have to implement like below
var emplist = ViewData['List'] #*(name should match with the controller)*#
var list=emplist as employeemodel #*(this is my model class name)*#
foreach(var item in list)
{
<li>#item.EmployeeName</li>
}

Opening a file in a new tab of the web browser

I have a view which shows a list of xml files in a directory. Also i have a button which would display the content of the file name selected in the browser. Currently its showing the content in a the same tab. But i want to display it in a new tab of the browser..
for example if i select two file names from the list, then it should open different tab for both the files..
Please find the code below.
public ActionResult ViewFile(string[] Name)
{
byte[] ImageData = null;
for (int i = 0; i < Name.Length; i++)
{
string filepath = holdpath + #"\" + Name[i];
string result;
using (StreamReader streamReader = new StreamReader(filepath))
{
result = streamReader.ReadToEnd();
}
using (System.IO.MemoryStream memoryStream = new System.IO.MemoryStream())
{
Document document = new Document(PageSize.A4, 10, 10, 10, 10);
PdfWriter writer = PdfWriter.GetInstance(document, memoryStream);
document.Open();
Paragraph paragraph = new Paragraph();
paragraph.Add(result);
document.Add(paragraph);
document.Close();
ImageData = memoryStream.ToArray();
}
}
Response.AppendHeader("Content-Disposition", "inline; filename=MyFile.pdf");
return File(ImageData, "application/pdf");
}
Please note that i am using itextsharp because the file also needs to be downloaded as pdf if required
I have added the View here
#model IEnumerable<FileInfo>
#{
ViewBag.Title = "files";
}
<h2>Held files</h2>
#using (Html.BeginForm())
{
<div style="border:solid;width:100%;overflow-x:auto;">
<table align="center" style="width:100%">
<thead>
<tr>
<th>File Name</th>
<th>Action</th>
</tr>
</thead>
<tbody>
#foreach (FileInfo file in Model)
{
<tr>
<td>
<input type="checkbox" name="Name" value="#file.Name" />
#file.Name
</td>
<td>
#Html.ActionLink("View", "ViewFile", "HoldFiles", new { Name = file.Name },
new { #class = "btn btn-primary btn-sm", target = "_blank" })
</td>
</tr>
}
</tbody>
</table>
</div>
}
In your view, put target="_blank" on your anchor element.
For example:
Open in new tab
or if using razor:
#Html.ActionLink("Text", "ActionMethodName", "ControllerName", new { id = Model.Id }, new { #class = "btn btn-primary btn-sm", target = "_blank" })

how to display 10 first rows from excel sheet with asp.net mvc 5

I need to display just 10 first rows from my excel sheet, i can only display all the excel data using "#Foreach".
please find the controller and the view below.
this is how i extract data from excel:
string path2 = "D:/Project/SesameIncident.xlsx";
Excel.Application application2 = new Excel.Application();
Excel.Workbook workbook2 = application2.Workbooks.Open(path2);
Excel.Worksheet worksheet2 = workbook2.ActiveSheet;
Excel.Range range2 = worksheet2.UsedRange;
List<SesameIn> ListSesame = new List<SesameIn>();
for (int row = 2; row <= range2.Rows.Count; row++)
{
SesameIn Se = new SesameIn();
Se.AssignedGroup= (((Excel.Range)range2.Cells[row, 1]).Text);
Se.Open = (((Excel.Range)range2.Cells[row, 2]).Text);
Se.Assigned = (((Excel.Range)range2.Cells[row, 3]).Text);
Se.PendingCustomer = (((Excel.Range)range2.Cells[row, 4]).Text);
Se.ClosedComplete = (((Excel.Range)range2.Cells[row, 5]).Text);
Se.Resolved = (((Excel.Range)range2.Cells[row, 6]).Text);
Se.Total = (((Excel.Range)range2.Cells[row, 7]).Text);
ListSesame.Add(Se);
}
ViewBag.ListSesames = ListSesame;
and this is the view code :
<div class="item">
<h1><img src="~/Web/PendingCustomer.png" /> Sesame Pending Tickets </h1>
<table class="table table-striped">
<thead>
<th>Number</th>
<th>Assigned To</th>
<th>Opened</th>
<th>Priortity</th>
<th>Assigned Group</th>
</thead>
<tbody>
#foreach (var In in ViewBag.ListSesameIncidents)
{
<tr>
#if (#In.Status == "Pending Customer")
{
<td>#In.Number</td>
<td>#In.AssignedTo</td>
<td>#In.Opened</td>
<td>#In.Priority </td>
<td>#In.Status</td>
<td>#In.AssignedGroup</td>
}
</tr>
}
</tbody>
</table>
<br />
<div class="carousel-caption">
</div>
</div>
I would suggest use Linq extension methods and filter the Data.
ViewBag.ListSesames = ListSesam
.Where(x=>x.Status == "Pending Customer") // Look for pending customers
.Take(10); // Take top 10
You can use linq .Take(10) to show the first 10 items.

Categories