excel report not download, what need to do more? - asp.net-mvc

Below code works well when I use a Submit button and put Excel export code in controller POST action.
Now I don't want post back and move the code like below, but now report is not download, although controller action "ExcelExport" called as expected, but report is not downloaded? Kindly suggest whats wrong here?
Model
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public Decimal Price { get; set; }
public Product(int id, string name, string description, decimal price)
{
Id = id;
Name = name;
Description = description;
Price = price;
}
static readonly List<Product> AllProducts = new List<Product>
{
new Product(1, "Games Console", "Fun for all the family", 199.99m),
new Product(2, "MP3 player", "Listen to your favourite tunes on the move", 99.99m),
new Product(3, "Smart Phone", "Apps, apps, apps", 399.99m),
new Product(4, "Digital Photo frame", "All your photos in one beautiful frame", 49.99m),
new Product(5, "E-book reader", "Take your favourite books on the move with you", 149.99m),
new Product(6, "DVD Box Set", "All of season one plus exclusive extras", 39.99m)
};
public static List<Product> GetAllProducts()
{
return AllProducts;
}
Controller
public ActionResult Index()
{
return View();
}
public ActionResult ExcelExport()
{
var products = Product.GetAllProducts();
var grid = new GridView();
grid.DataSource = from p in products
select new
{
ProductName = p.Name,
SomeProductId = p.Id
};
grid.DataBind();
Response.ClearContent();
Response.AddHeader("content-disposition", "attachment; filename=MyExcelFile.xls");
Response.ContentType = "application/excel";
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
grid.RenderControl(htw);
Response.Write(sw.ToString());
Response.End();
return Content("tr");
}
View
#{
ViewBag.Title = "Index";
}
#using (Html.BeginForm())
{
<div id="rptExport" style="display: none">
</div>
<input type="button" id="ExportExcelButton" value="Export To Excel" onclick="ExportExcel()" />
}
<script type="text/javascript">
//global cache false
$.ajaxSetup({ cache: false });
function ExportExcel() {
//block the UI until the request is rendered
$.blockUI({ message: '<h3><b><img src="#Url.Content("~/content/images/loading.gif")" />Please wait while Processing</b></h3>' });
$('#rptExport').load('#Url.Action("ExcelExport", "Home")', function (data) {
var urlFile = "";
if (data != '') {
debugger;
//unblock the UI
$.unblockUI();
}
});
}

You cannot use AJAX to download a file.
You need to use a regular page request.

Related

Multiple Checkbox with Model returns null

after I read data from my database, I try to show those datas in Html.Helper checkbox and I do that. But later when I try to get checked values back to the controller, model always returns null. Here's my controller part:
[HttpGet]
public ActionResult NewClient()
{
HizmetModel hizmetModel = new HizmetModel();
hizmetModel.hizmet = db.Hizmet.ToList<Hizmet>();
return View(hizmetModel);
}
[HttpPost]
public ActionResult NewClientPost(string name, string lastname, string telephone, string plate, HizmetModel hizmet)
{
Musteri musteri = new Musteri();
if (!db.Musteri.Where(x => x.plaka == plate).Any())
{
musteri.isim = name;
musteri.soyisim = lastname;
musteri.telefon = telephone;
musteri.plaka = plate;
db.Musteri.Add(musteri);
db.SaveChanges();
}
Islem islem = new Islem();
IslemHizmet islemhizmet = new IslemHizmet();
islem.giristarihi = DateTime.Now;
islem.plaka = plate;
var selectedHizmet = hizmet.hizmet.Where(x => x.isChecked == true).ToList<Hizmet>();
db.Islem.Add(islem);
db.SaveChanges();
var onprocessplate = db.Islem.Where(x => x.plaka == plate).FirstOrDefault();
foreach (var item in selectedHizmet)
{
islemhizmet.islem_id = onprocessplate.islem_id;
islemhizmet.hizmet_id = item.hizmet_id;
db.IslemHizmet.Add(islemhizmet);
db.SaveChanges();
islemhizmet = new IslemHizmet();
}
TempData["Success"] = "Müşteri başarıyla eklendi...";
return RedirectToAction("CurrentClients", "Admin");
}
This is my model for the list:
public class HizmetModel
{
public List<Hizmet> hizmet { get; set; }
}
I use this model in the cshtml file:
#model otoyikama.Models.Model.HizmetModel
And this is the loop for displaying checkboxes
#for (int i = 0; i < Model.hizmet.Count; i++)
{
<li>
<label>#Model.hizmet[i].hizmetisim</label>
#Html.CheckBoxFor(m => m.hizmet[i].isChecked)
#Html.HiddenFor(m => m.hizmet[i].hizmet_id)
#Html.HiddenFor(m => m.hizmet[i].hizmetisim)
</li>
}
I couldn't figure what's the problem here, my get action works fine, I can see all the data from database but I can't pass them back to controller.
As a first think , u need to create a object in your controller parameters such as like List<int> serviceIDs or List<Service> services so you can keep more data than one.
The html part:
#foreach(item in Model.Service)
{
<label>#item.ServiceName</label><br>
<input type="checkbox" name="services" value="#item.ServiceID">
<input type="hidden" name="services" value="#item.ServiceName">
}
The backend part:
[HttpPost]
public ActionResult NewClientPost(string name, string lastname, string telephone, string plate, List<Service> services)
{
}
when u do in that way, u will able to hold more services than to one and i think u can pass them the controller more easly.
when i face with that stuation, im taking those services ID's and calling them on the controller side like bellow;
The html part:
#foreach(item in Model.Service)
{
<label>#item.ServiceName</label><br>
<input type="checkbox" name="serviceIDs" value="#item.ServiceID">
}
The backend part:
[HttpPost]
public ActionResult NewClientPost(string name, string lastname, string telephone, string plate, List<int> serviceIDs)
{
List<Service> services= new List<Service>();
foreach(var item in serviceIDs)
{
var service=db.Service.Where(x => x.ServiceID == item).Any()
if(service.Count!=0)
{
services.Add(service);
}
}
}

How to save changes of courses in EmployeeCourse table

What i Need
I need to save changes in courses in EmployeeCourse table
by remove all course for employee from EmployeeCourse table
then add courses after changes
Problem
when add changes in courses after remove i get error in save changes() function
{"An error occurred while updating the entries.
The INSERT statement conflicted with the FOREIGN KEY constraint
\"FK_EmployeeCourse_Course\". The conflict occurred in database \"mycourse\",
table \"dbo.Course\", column 'Id'.\r\nThe statement has been terminated."}
under submit button edit [httppost]
public ActionResult Edit(EditEmployeeVm model)
{
var emp = db.Employees.FirstOrDefault(f => f.Id == model.Id);
// remove all courses
foreach (EmployeeCourse eec in emp.EmployeeCourses.ToList())
{
var ec = db.EmployeeCourses.Find(eec.Id);
db.EmployeeCourses.Remove(ec);
}
// add courses again
foreach (var couseid in model.CourseIds)
{
db.EmployeeCourses.Add(new EmployeeCourse { CourseId = couseid, EmployeeId = emp.Id });
}
db.SaveChanges();
}
Debug result
debug add as image below
Details
Relation between two tables one to many
EmployeeCourse
Id(primary key) CourseId(forign key) EmployeeId(forign key)
Course table in database
Id(pk) CourseName
I using following view model for edit to get CourseIds
#model StudentCourses.Models.EditEmployeeVm
$(function () {
$(document).on("click", ".remove", function (e) {
e.preventDefault();
$(this).closest(".course-item").remove();
});
$('#AvailableCourses').change(function () {
var val = $(this).val();
var text = $("#AvailableCourses option:selected").text();
var existingCourses = $("input[name='CourseIds']")
.map(function () { return this.value; }).get();
if (existingCourses.indexOf(val) === -1) {
var newItem = $("<div/>").addClass("course-item")
.append(text + ' Remove ');
newItem.append('<input type="text" name="CourseIds" value="' + val + '" />');
$("#items").append(newItem);
}
});
});
</script>
to retrieve courses from database in edit view i used code below
<div>
#using (Html.BeginForm())
{
#Html.HiddenFor(g => g.Id)
#Html.LabelFor(f => f.Name)
#Html.DropDownList("AvailableCourses", Model.Courses, "Select")
<h4>Existing courses</h4>
<div id="items"></div>
foreach (var c in Model.ExistingCourses)
{
<div class="course-item">
#c.Name Remove
<input type="text" name="CourseIds" value="#c.Id" />
</div>
}
}
</div>
model used for that as following
public class EditEmployeeVm
{
public int Id { set; get; }
public List<SelectListItem> Courses { get; set; }
public int[] CourseIds { set; get; }
public List<CourseVm> ExistingCourses { set; get; }
}
public class CourseVm
{
public int Id { set; get; }
public string Name { set; get; }
}
}
update
public ActionResult Edit(int id)
{
var vm = new EditEmployeeVm { Id = id };
var emp = db.Employees.FirstOrDefault(f => f.Id == id);
vm.Name = emp.Name;
vm.ExistingCourses = db.EmployeeCourses
.Where(g => g.EmployeeId == id)
.Select(f => new CourseVm
{
Id = f.Id,
Name = f.Course.CourseName
}).ToList();
vm.CourseIds = vm.ExistingCourses.Select(g => g.Id).ToArray();
vm.Courses = db.Courses.Select(f => new SelectListItem
{
Value = f.Id.ToString(),
Text = f.CourseName
}).ToList();
return View(vm);
}
In your EDIT Get action, You are using the wrong id for CourseVm. It should be the Course Id, but you are setting the EmployeeCourse record/entity Id.
This should fix it.
vm.ExistingCourses = db.EmployeeCourses.Where(g => g.EmployeeId == id)
.Select(f => new CourseVm
{
Id = f.Course.Id,
Name = f.Course.CourseName
}).ToList();

How to pass model to partialview at run time?

ViewModel
public class ModelTypeViewModel
{
public virtual CheckRadioButton CRB { get; set; }
}
Controller
public class M1Controller : Controller
{
public CarContext db = new CarContext();
private CheckRadioButton get()
{
CheckRadioButton c = new CheckRadioButton();
c.BrandName = "abc";
c.type = "xyz";
return c;
}
public ActionResult Hello ()
{
CheckRadioButton s = get();
ModelTypeViewModel mm = new ModelTypeViewModel(s);
return View(mm);
}
View:(Hello)
#model Car.Models.ModelTypeViewModel
#Html.Partial("_Display", Model.CRB)
Partial View(_Display)
<h1> Hello </h1>
How can I pass diff model each time to to partial view?
It gives an error
"An exception of type 'System.Web.HttpParseException' occurred in System.Web.WebPages.Razor.dll but was not handled in user code"
It gives the same error even if I pass only 'Model"
I am confused
Put each button inside Ajax.BeginForm
#using (Ajax.BeginForm("BuyItem", "MsmqTest"}, new AjaxOptions { UpdateTargetId = "msmqpartial" }))
{ <button type="submit">Buy</button>}
#using (Ajax.BeginForm("BuyItem", "MsmqTest" }, new AjaxOptions { UpdateTargetId = "msmqpartial" }))
{
<button type="submit">Sell</button>
}
Where "updateTargetId" is the div id to append content
public ActionResult BuyItem()
{
if(//some condition goes here)
return PartialView("Partial1",data);
if(//some condition goes here)
return PartialView("Partial2",data);
}

how to give textox dynamically at runtime in mvc4 bootstrap

HI i am new to mvc and bootstrap.. i want to dynamically add two text box at run time in mvc4 and bootstrap.. i have tried many sites but i am not able to understand. please give me simple example
i have tried this
In model
public class Gift
{
public string Name { get; set; }
public double Price { get; set; }
}
in controller
public ActionResult PanelEx()
{
var initialData = new[] {
new Gift { Name = "Tall Hat", Price = 39.95 },
new Gift { Name = "Long Cloak", Price = 120.00 },
};
return View(initialData);
}
what should i wrote in model. how to do next step..i am stuck PLese help
public ActionResult PanelEx()
{
var initialData = new List<Gift>{
new Gift { Name = "Tall Hat", Price = 39.95 },
new Gift { Name = "Long Cloak", Price = 120.00 },
};
return View(initialData);
}
#model IEnumerable<Gift>
<div>
#foreach(var item in Model)
{
<div>
#Html.TextBoxFor(item=>item.Name)
</div>
}
</div>

Add #Html.CheckBoxFor to email asp.net mvc 4

I have checkboxes in my feedback form, it looks like
I add checkboxes in my model
namespace CorePartners_Site2.Models
{
public class CareerForm
{
//...
public List<CheckBoxes> EmploymentType { get; set; }
}
public class CheckBoxes
{
public string Text { get; set; }
public bool Checked { get; set; }
}
}
add to my controller
[HttpGet]
public ActionResult CareerForm()
{
CareerForm model = new CareerForm();
model.EmploymentType = new List<CheckBoxes>
{
new CheckBoxes { Text = "Fulltime" },
new CheckBoxes { Text = "Partly" },
new CheckBoxes { Text = "Contract" }
};
return View(model);
}
but then I need to add selected checkboxes to email, but I dont know how to do it.
I tried
public ActionResult CareerForm(CareerForm Model, HttpPostedFileBase Resume)
{
System.Net.Mail.MailMessage msg = new System.Net.Mail.MailMessage();
msg.BodyEncoding = Encoding.UTF8;
string message = //...
"Type: " + Model.EmploymentType;
msg.Body = message;
//....
}
but I get in my email just text Type: System.Collections.Generic.List`1[CheckBoxes]
How to make it work right?
something like following
string message = "Type: ";
foreach(var item in Model.EmploymentType)
{
if (item.Checked)
message += item.Text;
}
Your model.EmploymentType is a List<CheckBoxes>
model.EmploymentType = new List<CheckBoxes>
You will have to access it's value with index. You are converting to string
a System.Collection.Generic.
You will need to get a the text values from each checked checkbox in your list.
This is a list:
model.EmploymentType = new List<CheckBoxes>...
You want the checked ones:
var checked = model.EmploymentType.Where(x => x.Checked);
Then you want the Text property from those boxes:
string message = "Type: " + checked.Text;
Put this together inside your controller action and I'd expect it to look like this:
public ActionResult CareerForm(CareerForm Model, HttpPostedFileBase Resume)
{
System.Net.Mail.MailMessage msg = new System.Net.Mail.MailMessage();
msg.BodyEncoding = Encoding.UTF8;
string message = "Type: ";
foreach(var box in Model.EmploymentType.Where(x => x.Checked)) {
message += box.Text + " ";
}
msg.Body = message;
}

Resources