Exporting a list to Excel and OpenOffice - asp.net-mvc

I have one list where I need to export data in excel. The Code in View:
$("#btnExport").click(function () {
//Used for Export to excel
window.open('#Url.Action("ExportHotelUtilizationListToExcel","DutyTravel")');
});
<input type="button" value="Export to Excel" name="submitButton" id="btnExport" class="k-button" />
and below is my controller method
public FileResult ExportHotelUtilizationListToExcel()
{
var grid = new System.Web.UI.WebControls.GridView();
List<DutyTravelHotelUtilization> lstSeparation = null;
if (Session["HotelUtilizationDetails"] != null)
{
lstSeparation = (List<DutyTravelHotelUtilization>)HttpContext.Session["HotelUtilizationDetails"];
grid.DataSource = from d in lstSeparation
select new
{
RequestCode = d.DutyTravelReqId,
StffNumber = d.StaffNumber,
StaffName = d.StaffName,
CityCode = d.CityCode,
CityName = d.CityName,
HotelCategory = d.HotelCategory,
HotelName = d.HotelName,
CurrencyInQAR = d.QurrencyQAR,
CheckInDate = Convert.ToDateTime(d.CheckInDate).ToString("dd-MMM-yyyy"),
CheckOutDate = Convert.ToDateTime(d.CheckOutDate).ToString("dd-MMM-yyyy"),
Duration = d.Duration
};
}
grid.DataBind();
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
grid.RenderControl(htw);
return File(new System.Text.UTF8Encoding().GetBytes(sw.ToString()), "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "Contacts.xlsx");
}
It is showing download option and able to open in OpenOffice but in MS Office 2010 showing error message about some format issue.

Related

Download Multiple Uploaded Files

I uploaded multiple files as bytes into database table and how to download files as zip now? My code as below:
View:
#using (Html.BeginForm(Html.BeginForm("upload", "Home", FormMethod.Post, new { #id = "form", enctype = "multipart/form-data" })))
{
<input type="file" multiple="multiple" name="files" id="files" />
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Submit" class="btn btn-default" />
</div>
</div>
}
controller:
public FileContentResult GetFile(int id)
{
SqlDataReader rdr; byte[] fileContent = null;
string mimeType = ""; string fileName = "";
string constr = WebConfigurationManager.ConnectionStrings["DbContextModel"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
var qry = "SELECT * FROM myTable WHERE ID = #ID";
var cmd = new SqlCommand(qry, con);
cmd.Parameters.AddWithValue("#ID", id);
con.Open();
rdr = cmd.ExecuteReader();
if (rdr.HasRows)
{
rdr.Read();
fileContent = (byte[])rdr["Attachments"];
}
}
return File(fileContent, "application/zip", "download.zip");
}
Model:
public partial class myTable
{
public int id {get;set;}
public byte[] Attachments { get; set; }
}
The download.zip file cannot be opened. "The compressed zipped folder is invalid". Please advise. Thanks in advance.
upload function:
...
byte[] bytes = new byte[] { 0x20, 0x20, 0x20, 0x20, 0x20, 0x20 };
MemoryStream target = new MemoryStream();
foreach (var file in files)
{
if (file.ContentLength > 0)
{
file.InputStream.CopyTo(target);
bytes = target.ToArray();
}
}
Appending the data for each uploaded file into a single stream doesn't create a valid zip file. You need to generate a valid zip file to store in the database.
For example:
byte[] bytes;
var target = new MemoryStream();
using (var zip = new ZipArchive(target, ZipArchiveMode.Create, true))
{
foreach (var file in files)
{
string name = Path.GetFileName(file.FileName);
ZipArchiveEntry entry = zip.CreateEntry(name);
using (Stream entryStream = entry.Open())
{
file.InputStream.CopyTo(entryStream);
}
}
bytes = target.ToArray();
}
ZipArchive Class

How to make a Web API Post Method trigger in a Html Form submit?

Currently I have a Web API Controller with a Post Method [form body] which does a post using PostMan to the Database.
Now the only thing I want to do is have that post method in the Web API work when a Html form='post' is submitted then let it post to the database. But How to make this happen?
Hey Everyone I was able to answer my own question, just for future viewers here's what I did
Html form with ajax:
<form method="post" action="Api/Values/Complex" enctype="application/x-www-form-urlencoded">
<select id="thisSelect">
<option value="sp18br"> sp18br</option>
<option value="sp18cl"> sp18cl</option>
</select>
<br />
<br />
<input type="submit" value="submit" />
</form>
<script>
$("form").on("submit", function () {
var post = $.post("api/values/complex", { "": $("#thisSelect").val() });
return false;
});
</script>
ValuesController.cs:
[HttpPost]
[ActionName("Complex")]
public HttpResponseMessage Post([FromBody]string value)
{
if (value == "sp18br")
{
string cadena = "Provider = Microsoft.Jet.OLEDB.4.0; Data Source = C:\\Users\\azib\\Desktop\\dfb; Extended Properties = dBASE IV; User ID = Admin; Password =";
string select = "Select * from sp18br ";
DataSet myDataSet = new DataSet();
OleDbConnection con = new OleDbConnection(cadena);
OleDbCommand myAccessCommand = new OleDbCommand(select, con);
OleDbDataAdapter myDataAdapter = new OleDbDataAdapter(myAccessCommand);
con.Open();
DataTable dt = new DataTable();
myDataAdapter.Fill(dt);
con.Close();
string cs = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
using (SqlConnection con1 = new SqlConnection(cs))
{
con1.Open();
foreach (DataRow dr1 in dt.Rows)
{
SqlCommand cmd = new SqlCommand("sp_InsertLeafPickup", con1);
cmd.CommandType = CommandType.StoredProcedure;
//Insert stored procedure
cmd.Parameters.AddWithValue("#Address", dr1["PCOMBINED"]);
//cmd.Parameters.AddWithValue("#SeasonType", dr1["PSSSTREET"]);
cmd.Parameters.AddWithValue("#NextPickupdate", dr1["ZST"]);
cmd.ExecuteNonQuery();
}
con.Close();
con1.Close();
}
return Request.CreateResponse(HttpStatusCode.OK, "Ok");
}
if (value == "sp18cl")
{
string cadena1 = "Provider = Microsoft.Jet.OLEDB.4.0; Data Source = C:\\Users\\azib\\Desktop\\dfb; Extended Properties = dBASE IV; User ID = Admin; Password =";
string select1 = "Select * from sp18cl ";
DataSet myDataSet1 = new DataSet();
OleDbConnection con2 = new OleDbConnection(cadena1);
OleDbCommand myAccessCommand1 = new OleDbCommand(select1, con2);
OleDbDataAdapter myDataAdapter1 = new OleDbDataAdapter(myAccessCommand1);
con2.Open();
DataTable dt1 = new DataTable();
myDataAdapter1.Fill(dt1);
con2.Close();
string cs1 = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
using (SqlConnection con3 = new SqlConnection(cs1))
{
con3.Open();
foreach (DataRow dr1 in dt1.Rows)
{
SqlCommand cmd = new SqlCommand("sp_InsertLeafPickup", con3);
cmd.CommandType = CommandType.StoredProcedure;
//Insert stored procedure
cmd.Parameters.AddWithValue("#Address", dr1["PCOMBINED"]);
// cmd.Parameters.AddWithValue("#SeasonType", dr1["PSSSTREET"]);
cmd.Parameters.AddWithValue("#NextPickupdate", dr1["ZST"]);
cmd.ExecuteNonQuery();
}
con2.Close();
con3.Close();
}
}
return Request.CreateResponse(HttpStatusCode.OK, "Ok");
}

How to retain text box values after postback in asp.net mvc

I have 2 form in the single view and below are the code.
#model MCRP.Models.tblRequest
#{
ViewBag.Title = "Review Request";
}
#using (Html.BeginForm("InsertForm", "Home"))
{
#Html.EditorFor(model => model.ContactEmailAddress, new { htmlAttributes = new {id = "txtdelivery"} })
<input type="submit" onclick="return validate();" value="submit" id="submitfilteration" class="btn btn-primary pull-left" />
}
#using (Html.BeginForm("Delete", "Home"))
{
Are you sure you want to delete Property ?
<input type="submit" value="Delete" class="btn btn-danger" />
}
But on click of delete button, the text inserted in the txtdelivery get disappear
Controller
public ActionResult ReviewRequest()
{
if (Session["AddtoCart"] != null)
{
DataTable dt = (DataTable)Session["AddtoCart"];
if (dt.Rows.Count > 0)
{
ViewBag.addedtocart = (DataTable)Session["AddtoCart"];
}
else
{
ViewBag.addedtocart = null;
ViewBag.EmptyCart = "Your Cart Is empty";
}
}
else
{
ViewBag.addedtocart = null;
ViewBag.EmptyCart = "Your Cart Is empty";
}
return View();
}
public ActionResult InsertForm(tblRequest Request)
{
int requestid = 0;
int RequestProperty = 0;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("InsUpsDelTbl_Request"))
{
try
{
cmd.Connection = con;
cmd.CommandType = CommandType.StoredProcedure;
con.Open();
cmd.Parameters.AddWithValue("#Operation", "InsertRequest");
cmd.Parameters.AddWithValue("#AgencyName", Request.AgencyName);
cmd.Parameters.AddWithValue("#Contact", Request.Contact);
cmd.Parameters.AddWithValue("#DeliveryAddress", Request.DeliveryAddress);
cmd.Parameters.AddWithValue("#ContactPhone", Request.ContactPhone);
cmd.Parameters.AddWithValue("#ContactEmailAddress", Request.ContactEmailAddress);
cmd.Parameters.AddWithValue("#Notes", Request.Notes);
requestid = Convert.ToInt32(cmd.ExecuteScalar());
con.Close();
}
catch (Exception ex)
{ throw ex; }
}
using (SqlCommand cmd = new SqlCommand("InsUpsDelTbl_Request"))
{
DataTable dt = new DataTable();
dt = (DataTable)Session["AddtoCart"];
try
{
if (dt.Rows.Count > 0)
{
cmd.Connection = con;
cmd.CommandType = CommandType.StoredProcedure;
con.Open();
for (int i = 0; i < dt.Rows.Count; i++)
{
cmd.Parameters.Clear();
cmd.Parameters.AddWithValue("#Operation", "InsertRequestProperty");
cmd.Parameters.AddWithValue("#RequestID", requestid);
cmd.Parameters.AddWithValue("#PropertyID", dt.Rows[i]["PropertyId"].ToString());
cmd.Parameters.AddWithValue("#Quantity", dt.Rows[i]["Quantity"].ToString());
RequestProperty= Convert.ToInt32(cmd.ExecuteScalar());
}
con.Close();
if (requestid > 0 && RequestProperty>0)
{
TempData["InsertRequestProperty"] = ConfigurationManager.AppSettings["RequestAdded"].ToString().Replace("{#requestid}", Convert.ToString(requestid));
Session["AddtoCart"] = null;
}
}
}
catch (Exception ex)
{ throw ex; }
}
}
return RedirectToAction("ReviewRequest");
}
public ActionResult Delete(FormCollection property)
{
string PropertyID = "";
foreach (var key in property.AllKeys)
{
PropertyID = property["hddeleteGroupid"];
}
DataTable dt = new DataTable();
if (Session["AddtoCart"] != null)
{
dt = (DataTable)Session["AddtoCart"];
for (int i = dt.Rows.Count - 1; i >= 0; i--)
{
DataRow dr = dt.Rows[i];
if (dr[0].ToString() == PropertyID)
{
dt.Rows.Remove(dr);
}
}
Session["AddtoCart"] = dt;
}
return RedirectToAction("ReviewRequest");
}
As I am new in MVC I don't know please help me out
More Detail My page more detail is as shown in figure
Now on click of delete one popup with delete dialog gets open and on pressing of delete button one item added in the cart get deleted and also the text inserted in textbox get disappear,

MVC gridview return popup with html when select filter or click next page

mvc gridview return popup with html when select filter or click next page how can I fix this problem in this code show my partial gridview my view and controller action
PartialView
#{
Html.DevExpress().GridView(settings =>
{
settings.Name = "TestList";
settings.CallbackRouteValues = new { Controller = "Admin", Action = "TestList" };
settings.CommandColumn.Visible = true;
settings.KeyFieldName = "ID";
settings.CommandColumn.Visible = false;
settings.Columns.Add(column =>
{
column.Caption = "Edit";
column.Visible = true;
column.SetDataItemTemplateContent(content =>
ViewContext.Writer.Write(
Html.ActionLink("Edit", "TestListEdit", "admin",
new { id = content.KeyValue }, null)));
});
settings.Columns.Add(column =>
{
column.Caption = "Delete";
column.Visible = true;
column.SetDataItemTemplateContent(content =>
ViewContext.Writer.Write(
Html.ActionLink("Delete", "TestListDelete", "admin",
new { id = content.KeyValue }, null)));
});
settings.Columns.Add(column =>
{
column.Caption = "Manage";
column.Visible = true;
column.SetDataItemTemplateContent(content =>
ViewContext.Writer.Write(
Html.ActionLink("Manage Questions", "ManageQuestions", "admin",
new { id = content.KeyValue }, null)));
});
settings.SettingsBehavior.AllowSelectByRowClick = true;
settings.Columns.Add("ID");
settings.Columns.Add("Title");
settings.Columns.Add("Description");
settings.Columns.Add("Lang_ID");
settings.Columns.Add("TryDescription");
}).Bind(Model).Render();
}
this is my View
#model List<FastCreditTraining.Models.AdminTestListEditingModel>
#{
ViewBag.Title = "TestList";
Layout = "~/Views/Shared/_adminLayout.cshtml";
}
#{
List<SelectListItem> listItems = new List<SelectListItem>();
listItems.Add(new SelectListItem
{
Text = "English",
Value = "1"
});
listItems.Add(new SelectListItem
{
Text = "Հայերեն",
Value = "2",
});
}
<body>
<div style="display:inline-block;float:right; margin-right:30px; margin-top:10px">
#Html.ActionLink("Create", "TestListCreate", "admin", new { #class = "LangButton" })
</div>
<div style="display:inline-block">
<form style="display:inline-block" name="tActive" id="tActive" method="get">
<div style="margin-left:50px; display:inline-block;">
<p style="display:inline-block">#Resources.Resource.DisplayActiveTests</p>
#Html.CheckBox("tActive", true)
</div>
<div style="margin-left:100px; display:inline-block;">
<p style="display:inline-block">#Resources.Resource.SetLanguageInterfaceEdit</p>
#Html.DropDownList("langSwitch", listItems)
</div>
<input type="submit" name=" asdasd" value="Filter">
</form>
</div></body>
#{Html.RenderPartial("_GridViewTestListPartial",Model);}
And this is my controller action
![\[Authorize\]
public ActionResult TestList(string tActive, string langSwitch)
{
//tActive and langSwitch choose getting tests with procedure getTests_Result
List model1;
if (tActive == null || langSwitch == null)
{
model1 = db.getTests(true, 1).ToList();
}
else
{
model1 = db.getTests(Convert.ToBoolean(tActive), Convert.ToInt32(langSwitch)).ToList();
}
///////////////////end of getting///////////////////
// Fill new created model from database test lists and departaments and positions
List _Departments = db.T_Department_Lang.ToList();
List _Positions = db.T_Position_Lang.ToList();
List _checkForDep = new List();
List _checkForPos = new List();
foreach (var item in _Departments)
{
_checkForDep.Add(new bool());
}
foreach (var item in _Positions)
{
_checkForPos.Add(new bool());
}
for (int i = 0; i < model1.Count; i++)
{
allModels.Add(new AdminTestListEditingModel()
{
ID = model1\[i\].ID,
Date_Added = model1\[i\].Date_Added,
Limit = model1\[i\].Limit,
IS_Active = model1\[i\].IS_Active,
Allow_Back = model1\[i\].Allow_Back,
Title = model1\[i\].Title,
Description = model1\[i\].Description,
Lang_ID = model1\[i\].Lang_ID,
S_Changed = model1\[i\].S_Changed,
Question_qnt = model1\[i\].Question_qnt,
Pos_Save = model1\[i\].Pos_Save,
Question_test_qnt = model1\[i\].Question_test_qnt,
TryDescription = model1\[i\].TryDescription,
qCount = model1\[i\].qCount,
TestList_Id = model1\[i\].ID,
Departments = _Departments,
Positions = _Positions,
checkForDep = _checkForDep,
checkForPos = _checkForPos
});
}
//////////////// end fill //////////////////
Session\["allModels"\] = allModels;
return View(allModels);
}][1]
Return PartialView instead of View to resolve this issue:
//return View(allModels);
return PartialView(allModels);
See the Why can the alert message with the HTML/JavaScript/CSS content appear when using callback-aware extensions? knowledge resource to learn more.

returning data from controller to VIEW

ii am told to create a login system in MVC 3 using old traditional sql queries etc, i have created login but problem is that i'm returning data from model to View . I have created datatable in model and returning it to controller, successfully but don't know that how to show that data on view ? have searched good but didn't help.
MODEL :
public ConnectionStatus Login_db(String email, String pwd, String conStr)
{
String hashedpwd_login = FormsAuthentication.HashPasswordForStoringInConfigFile(pwd, "SHA1");
using (SqlConnection sqlCon = new SqlConnection(conStr))
{
using (SqlCommand sqlCom = new SqlCommand())
{
sqlCom.Connection = sqlCon;
sqlCom.CommandText = "select Count(*) from tblRegister where userEmail=#email AND userPwd=#pwd";
sqlCom.Parameters.AddWithValue("#email", email);
sqlCom.Parameters.AddWithValue("#pwd", hashedpwd_login);
String select_com = "select * from tblRegister";
SqlCommand sqlCom2 = new SqlCommand(select_com, sqlCon);
ConnectionStatus connectStatus = new ConnectionStatus();
int no_rows_affected;
SqlDataAdapter sda = new SqlDataAdapter(select_com, sqlCon);
DataTable data_tb = new DataTable();
try
{
sqlCon.Open();
no_rows_affected = Convert.ToInt32(sqlCom.ExecuteScalar());
if (no_rows_affected == 1)
{
connectStatus.Message = "User logged in successfully, " + no_rows_affected;
sda.Fill(data_tb);
tableCreation tb_creation = new tableCreation();
tb_creation.CreateTable = data_tb;
}
else
{
connectStatus.Message = "Invalid email/password combination.";
}
}
catch (Exception ex)
{
connectStatus.Message = ex.Message;
}
return connectStatus;
}
}
}
Controller :
public ActionResult loginResult(String command, FormCollection formData)
{
if (command == "Login")
{
var email = formData["txtboxEmail"];
var pwd = formData["txtboxPassword"];
// String conStr = "Data Source=HUNAIN-PC;Initial Catalog=registration;User ID=sa;Password=abc123!##";
database model_db = new database();
var db_status = model_db.Login_db(email, pwd, conStr);
ViewBag.Message = db_status.Message;
}
tableCreation retTable = new tableCreation();
return View(retTable.CreateTable);
}
View:
#{
ViewBag.Title = "Login Authentication";
}
<h2>Login Authentication</h2>
<h4>#ViewBag.Message</h4>
Note: some classes are user defined for multi purposes.
You can use WebGrid in MVC3. This is new in MVC3. Use this code in your View.
#model IList<YourViewModel>
#{
ViewBag.Title = "Login Information";
Layout = "~/Views/Shared/_Layout.cshtml";
}
#{
var grid = new WebGrid(source: Model, rowsPerPage: 200,
canPage: false, canSort: true, defaultSort: "Absentee");
}
<p>
<h2>Absentee List</h2>
<div id="grid">
#grid.GetHtml(
tableStyle: "grid",
headerStyle: "head",
alternatingRowStyle: "alt",
columns: grid.Columns(
grid.Column(format: (item) => Html.ActionLink("Edit", "Edit",
new { id = item.Id })),
grid.Column("Absentee", "Absentee",canSort:true),
grid.Column("AbsStart", "AbsStartDate")
))
</div>
</p>

Resources