I have written some code based on some tutorials to update an existing word document with data from my database tables.
I keep getting the program crashing and advising that I may have an infinite loop, however I am using a for each statement and when I debug it tells me i only have one record. Cannot understand where the problem is.
If someone can assist that would be greatly appreciated. Code below
Controller
using System.Web.Mvc;
using Mojito.Models;
namespace Mojito.Controllers
{
public class KronosDesignDocumentController : Controller
{
private MojitoContext _db = new MojitoContext();
//
// GET: /KronosDesignDocument/
public ActionResult Index()
{
ViewBag.CustomerId = new SelectList(_db.Customers, "CustomerId", "CustomerName");
return View();
}
[HttpPost]
public ActionResult Load(int customerId)
{
var kronosDesignTemplate = new KronosDesignDocument.CreateDesignDoc(#"C:\Users\Craig Cocker\Documents\XML Files\Test_Design_Template.docx");
kronosDesignTemplate.CustomerDesignDocument();
ViewBag.CustomerId = new SelectList(_db.Customers, "CustomerId", "CustomerName");
ViewBag.Message = "Configuration has been loaded successfully";
return View("Index");
}
}
}
Model
using System.Collections.Generic;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;
using System.Linq;
namespace Mojito.Models
{
public class KronosDesignDocument
{
public static MojitoContext _db = new MojitoContext();
public class CreateDesignDoc
{
private readonly string _xmlPath;
//private readonly int _customerId;
public CreateDesignDoc(string pathToXmlFiles)
{
_xmlPath = pathToXmlFiles;
}
public IEnumerable<Customer> CustomerDesignDocument()
{
WordprocessingDocument myDoc = WordprocessingDocument.Open(_xmlPath, true);
var docPart = myDoc.MainDocumentPart;
var doc = docPart.Document;
var table = new Table();
var tb = new TopBorder();
tb.Val = BorderValues.DashDotStroked;
tb.Size = 12;
var borders = new TableBorders();
borders.TopBorder = tb;
borders.LeftBorder = new LeftBorder() {Val = BorderValues.Single, Size = 12};
borders.RightBorder = new RightBorder() {Val = BorderValues.Single};
borders.BottomBorder = new BottomBorder() {Val = BorderValues.Single};
borders.InsideHorizontalBorder = new InsideHorizontalBorder() {Val = BorderValues.Single};
borders.InsideVerticalBorder = new InsideVerticalBorder() {Val = BorderValues.Single};
var props = new TableProperties();
props.Append(borders);
table.Append(props);
var customers = _db.Customers.ToList();
var customerCollection = new List<Customer>();
foreach (var c in customers)
{
var tr = new TableRow();
var customerName = c.CustomerName;
var tc = new TableCell();
var runProp = new RunProperties();
runProp.Append(new Bold());
runProp.Append(new Color() {Val = "FF0000"});
var run = new Run();
run.Append(runProp);
var t = new Text(customerName);
run.Append(t);
var justification = new Justification();
justification.Val = JustificationValues.Center;
var paraProps = new ParagraphProperties(justification);
var p = new Paragraph();
p.Append(paraProps);
p.Append(run);
tc.Append(p);
var tcp = new TableCellProperties();
var tcw = new TableCellWidth();
tcw.Type = TableWidthUnitValues.Dxa;
tcw.Width = "2000";
tcp.Append(tcw);
tcp.Append(tcp);
tr.Append(tc);
table.Append(tr);
}
doc.Body.Append(table);
doc.Save();
return customerCollection;
}
}
}
}
View
#model Mojito.Models.KronosDesignDocument
#{
ViewBag.Title = "Kronos Design Document";
}
<h1>Load Kronos Data</h1>
<h2>#ViewBag.Message</h2>
#using (Html.BeginForm("Load", "KronosDesignDocument", FormMethod.Post))
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<hr />
#Html.ValidationSummary(true)
<div class="form-group">
<div>#Html.Partial("~/Views/Shared/_Customer.cshtml")</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<label for="file">Filename:</label>
<input type="file" name="file" id="file" />
<input type="submit" value="Create Design Document" class="btn btn-default" />
</div>
</div>
</div>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
In your method to create your document you have this line:
tcp.Append(tcp);
that basically appends a reference to its self. I assume the OpenXML stuff expects you to take care of peventing such self-references and if you don't it's only way it has left is break with an StackOverflow exception.
If you fix that line, to
tc.Append(tcp);
all is good...
Related
I am making a tweak to an app and doing an UPDATE. It throws me the following error:
There is no ViewData item of type 'IEnumerable' that has the key 'Conve'.
My DropDownList loads the data perfectly but when I select any of that list to use its value and change it to the value that is in my BD it throws that error
Model: TableAsign.cs
public class TableAsign
{
public long IdCliente { get; set; }
public string nombre { get; set; }
}
Controller: MastController.cs
[Authorize]
public ActionResult Asign_Conv(int idUsuario)
{
List<Models.TableAsign> lst = null;
using (TPConveniosEntities db = new TPConveniosEntities())
{
lst = (from d in db.Cliente
orderby d.nombre
select new TableAsign
{
IdCliente = d.idCliente,
nombre = d.nombre
}).ToList();
}
List<SelectListItem> items = lst.ConvertAll(d =>
{ return new SelectListItem()
{ Text = d.nombre.ToString(),
Value = d.IdCliente.ToString(),
Selected = false
};
});
ViewBag.items = items;
using (TPConveniosEntities db = new TPConveniosEntities())
{
Usuario user = db.Usuario.FirstOrDefault(u => u.idUsuario == idUsuario);
return View(user);
}
}
In this part it performs the UPDATE and it seems to me that it has to do when I bring the value of my DropDownList with my long variable, it throws me the error and then when I consult my DB I see that if it performs the UPDATE but giving me that error
[Authorize]
[HttpPost]
public ActionResult Asign_Conv(FormCollection collection)
{
using (TPConveniosEntities contexto = new TPConveniosEntities())
{
var idUsuario = Convert.ToInt32(collection["IdUsuario"].Trim());
Usuario user = contexto.Usuario.FirstOrDefault(u => u.idUsuario == idUsuario);
var userName = collection["usuario"].Trim();
long IdCliente = Convert.ToInt32(collection["Convenio"].Trim());
user.userName = userName;
user.idCliente = IdCliente;
contexto.SaveChanges();
return View(user);
}
}
VIEW: Asign_Conv.cshtml
#using TPConvenios.App_Data;
#model Usuario
#{
Layout = null;
AjaxOptions ajaxOpciones = new AjaxOptions
{
UpdateTargetId = "cuerpoPopUpGenerico2",
InsertionMode = InsertionMode.Replace,
OnSuccess = "OnSuccess_Asign",
OnFailure = "OnFailure"
};
List<SelectListItem> items = (List<SelectListItem>)ViewBag.items;
}
<div id="contenedor" style="margin: 15px 30px">
#using (Ajax.BeginForm("Asign_Conv", "Mast", null, ajaxOpciones, new { id = "Asign_Conv" }))
{ #Html.ValidationSummary(true);
<input type="hidden" name="idUsuario" id="idUsuario" value="#(null != Model ? Model.idUsuario : 0)" />
<p>
<input name="usuario" type="text" id="usuario" class="usuario" placeholder="Usuario" value="#(null != Model ? Model.userName : String.Empty)"/>
</p>
<p>
#Html.DropDownList("Convenio", items, "Seleccione el Convenio", new { #class = "form-control" })
</p>
<p id="bot">
<input name="submit" type="submit" id="submit" value="Asignar" class="botonNuevo" style="float: right" />
</p>
}
</div>
I managed to solve my problem by bringing me the code with which I load my DropdownList, and pasting it to the POST where it performs UPDATE.
staying this way
[Authorize]
[HttpPost]
public ActionResult Asign_Conv(FormCollection collection)
{
using (TPConveniosEntities contexto = new TPConveniosEntities())
{
var idUsuario = Convert.ToInt32(collection["IdUsuario"].Trim());
Usuario user = contexto.Usuario.FirstOrDefault(u => u.idUsuario == idUsuario);
var userName = collection["usuario"].Trim();
long IDCliente = Convert.ToInt32(collection["Conve"].Trim());
/*********** ESTO FUE LO QUE COPIE PARA QUE FUNCIONARA **********/
List<Models.TableAsign> lst = null;
using (TPConveniosEntities db = new TPConveniosEntities())
{
lst = (from d in db.Cliente
orderby d.nombre
select new TableAsign
{
IdCliente = d.idCliente,
nombre = d.nombre
}).ToList();
}
List<SelectListItem> items = lst.ConvertAll(d =>
{
return new SelectListItem()
{
Text = d.nombre.ToString(),
Value = d.IdCliente.ToString(),
Selected = false
};
});
ViewBag.items = items;
/*************************** HASTA AQUI **********************/
user.userName = userName;
user.idCliente = IDCliente;
contexto.SaveChanges();
return View(user);
}
}
I need help to get a solution to a question. The case is as follows:
We are working on a group project with asp.net, c #, javascript, html and razor technologies.
The structure of projects within the solution is as follows:
1.POJO-entities: where the models are located.
2.DataAccess: it is divided into three folders: 1. Crud (where are the classes that contain the "crudfactory" of each Pojo, 2. Dao (find the connection to the database, in this case SQL Server) and finally, the Mapper
3.CoreApi, where are the managers of each well.
4.WebApi, where are the controllers of each well.
5.WepApp, where is the UI (cshtmls) and javascripts.
Now, I have to implement a virtual wallet that can be topped up via PayPal and I have a method that receives the price and the description of the payment, for now it is "burned", but it must be parameterizable. I want to know if I can take the value of CtrlInput and put it in the HTMLAtributes of my ActionLink.
The idea may remove the # Html.ActionLink and leave the functionality in the "Update", but I don't know how to send the parameters from the view JS to the PayPal controller.
This is the javascript code for the wallet view:
function vMonedero() {
//this.tblMonederoId = 'tblMonedero';
this.service = 'monedero';
this.ctrlActions = new ControlActions();
this.columns = "IdUsuario, IdMonedero, Monto";
this.paypal = new PaymentWithPayPal();
this.RetrieveAll = function () {
this.ctrlActions.FillTable(this.service, this.tblMonedero, false);
}
this.Create = function () {
var monederoData = {};
monederoData = this.ctrlActions.GetDataForm('frmEdition');
if (monederoData["Monto"] == "") {
this.ctrlActions.ShowMessage('E', "Favor ingresar el nuevo valor");
}
else if (isNaN(monederoData["Monto"])) {
this.ctrlActions.ShowMessage('E', "Favor ingresar un valor numérico");
}
else {
this.ctrlActions.PostToAPI(this.service, monederoData);
}
}
this.Update = function () {
var monederoData = {};
monederoData = this.ctrlActions.GetDataForm('frmEdition');
price = monederoData["Monto"];
paypal.PaymentWithPayPal(price, "Recarga de monedero");
//Hace el post al create
this.ctrlActions.PutToAPI(this.service, monederoData);
//Refresca la tabla
}
this.Delete = function () {
var monederoData = {};
monederoData = this.ctrlActions.GetDataForm('frmEdition');
//Hace el post al create
this.ctrlActions.DeleteToAPI(this.service, monederoData);
//Refresca la tabla
}
this.BindFields = function (data) {
this.ctrlActions.BindFields('frmEdition', data);
}
}
//ON DOCUMENT READY
$(document).ready(function () {
var vmonedero = new vMonedero();
//vmonedero.RetrieveAll();
});
This is the view code:
#using WebApp.Helpers;
<script src="~/Scripts/Views/vMonedero.js"></script>
<script src="https://www.paypalobjects.com/api/checkout.js"></script>
#{
Layout = "~/Views/Shared/_Layout.cshtml";
}
<div class="card border-secondary" style="margin-top: 50px;">
<div class="card-header">
<div class="row pull-right">
<div class="col-md-8">Monedero</div>
<div class="col-md-4">
#Html.CtrlButton(viewName: "vMonedero", id: "btnCreate", label: "Crear", onClickFunction: "Create", buttonType: "success")
#Html.CtrlButton(viewName: "vMonedero", id: "btnUpdate", label: "Recargar", onClickFunction: "Update", buttonType: "info")
</div>
</div>
</div>
<div class="card-body">
<div class="row">
<div class="col-lg-6">
<div class="bs-component">
<form id="frmEdition">
#Html.CtrlInput(id: "txtIdUsuario", type: "text", label: "N° de identificación", columnDataName: "IdUsuario")
#Html.CtrlInput(id: "txtIdMonedero", type: "text", label: "N° de monedero", columnDataName: "IdMonedero")
#Html.CtrlInput(id: "txtIdMonto", type: "text", label: "Monto", columnDataName: "Monto")
#* #Html.CtrlDropDown(id: "drpGender", label: "Gender", listId: "LST_GENERO")*#
</form>
</div>
</div>
</div>
</div>
</div>
#*<script>
$('#price').click(function () {
var monederoData = {};
ctrlActions = new ControlActions();
ctrlActions.GetDataForm('frmEdition');
monederoData["Monto"] = price;
return price;
});
</script>*#
Paypal Controller Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using PaymentPayPal.Models;
using PayPal.Api;
namespace WebApp.Controllers
{
public class PayPalController : Controller
{
// GET: PayPal
public ActionResult Index()
{
return View();
}
public ActionResult PaymentWithPaypal(string price, string product)
{
//getting the apiContext as earlier
APIContext apiContext = ConfigurationPayPal.GetAPIContext();
try
{
string payerId = Request.Params["PayerID"];
if (string.IsNullOrEmpty(payerId))
{
string baseURI = Request.Url.Scheme + "://" + Request.Url.Authority +
"/Paypal/PaymentWithPayPal?";
var guid = Convert.ToString((new Random()).Next(100000));
var createdPayment = this.CreatePayment(apiContext, baseURI + "guid=" + guid, price, product);
var links = createdPayment.links.GetEnumerator();
string paypalRedirectUrl = null;
while (links.MoveNext())
{
Links lnk = links.Current;
if (lnk.rel.ToLower().Trim().Equals("approval_url"))
{
paypalRedirectUrl = lnk.href;
}
}
Session.Add(guid, createdPayment.id);
Console.WriteLine(createdPayment.id);
return Redirect(paypalRedirectUrl);
}
else
{
var guid = Request.Params["guid"];
Console.WriteLine("Session:" + Session[guid] as string);
var executedPayment = ExecutePayment(apiContext, payerId, Session[guid] as string);
if (executedPayment.state.ToLower() != "approved")
{
return View("FailureView");
}
}
}
catch (Exception ex)
{
return View("FailureView");
}
return View("SuccessView");
}
private PayPal.Api.Payment payment;
private Payment ExecutePayment(APIContext apiContext, string payerId, string paymentId)
{
var paymentExecution = new PaymentExecution() { payer_id = payerId };
this.payment = new Payment() { id = paymentId };
return this.payment.Execute(apiContext, paymentExecution);
}
private Payment CreatePayment(APIContext apiContext, string redirectUrl, string price, string product)
{
var itemList = new ItemList() { items = new List<Item>() };
itemList.items.Add(new Item()
{
name = product,
currency = "USD",
price = price,
quantity = "1",
sku = "sku"
});
var payer = new Payer() { payment_method = "paypal" };
var redirUrls = new RedirectUrls()
{
cancel_url = redirectUrl,
return_url = redirectUrl
};
// similar as we did for credit card, do here and create details object
var details = new Details()
{
tax = "1",
shipping = "1",
subtotal = price
};
// similar as we did for credit card, do here and create amount object
var amount = new Amount()
{
currency = "USD",
total = "" + (int.Parse(price) + 1 + 1), // Total must be equal to sum of shipping, tax and subtotal.
details = details
};
var transactionList = new List<Transaction>();
transactionList.Add(new Transaction()
{
description = "Transaction description.",
invoice_number = Convert.ToString((new Random()).Next(100000)),
amount = amount,
item_list = itemList
});
this.payment = new Payment()
{
intent = "sale",
payer = payer,
transactions = transactionList,
redirect_urls = redirUrls
};
// Create a payment using a APIContext
return this.payment.Create(apiContext);
}
}
}
I am working with Jira Rest Api and I am trying to create a form that will include a dropdown with all the users from certain project, so I could assign them while creating a ticket.
My form works But unfortunnetly Users have to be hardcoded at the moment.
I am a novice programmer and my problem begins here: I am usign HttpPost to submit form and pass that values to Api, but before I do that I need to do HttpGet to populate one of the form dropdowns. This is confusing for me and I am not able to do that.
My Form
#using (Html.BeginForm("Index", "Ticket", FormMethod.Post))
{
<div>
<br />
<div style="background-color:#1976D2; color: white; padding: 3px; border-radius:3px; font-weight: 300;">
<a>Create Issue</a>
</div>
<br />
<form>
<span style="font-size: 0.9em">Project</span> #Html.DropDownListFor(m => model.fields.project.key, new List<SelectListItem> { new SelectListItem { Text = "Jira Test Board", Value = "JATP" }, }, new { #class = "form-control input-background" })
<br />
<span style="font-size: 0.9em">Issue type</span> #Html.DropDownListFor(m => model.fields.issuetype.name, new List<SelectListItem> { new SelectListItem { Text = "Sales", Value = "Sales" }, new SelectListItem { Text = "Bug", Value = "Bug" }, new SelectListItem { Text = "Feature", Value = "Feature" }, new SelectListItem { Text = "Task", Value = "Task" }, }, new { #class = "form-control input-background" })
<br />
<span style="font-size: 0.9em">Assign<sup class="star">*</sup></span> #Html.DropDownListFor(m => model.fields.assignee.name, new List<SelectListItem> { new SelectListItem { Text = "Jacob Zielinski", Value = "<someId>" }, }, new { #class = "form-control input-background" })
<br />
<span style="font-size: 0.9em">Summary<sup class="star">*</sup></span> #Html.TextBoxFor(m => model.fields.summary, new { #class = "form-control my-size-text-area input-background" })
<br />
<div class="form-group">
<span style="font-size: 0.9em">Description<sup class="star">*</sup></span> #Html.TextAreaFor(m => model.fields.description, 5, 60, new { #class = "form-control my-size-text-area input-background" })
</div>
<br />
<input onclick="loadingOverlay()" id="Submit" class="btn btn-primary float-right" type="submit" value="Create" />
</form>
</div>
}
Ticket Controller
public class TicketController : Controller
{
[HttpPost]
public async Task<ActionResult> Index(TokenRequestBody model)
{
var submitForm = new TokenRequestBody()
{
fields = new TokenRequestField()
{
project = model.fields.project,
description = model.fields.description,
summary = model.fields.summary,
issuetype = model.fields.issuetype,
assignee = model.fields.assignee
},
};
using (var httpClient = new HttpClient())
{
httpClient.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue(
"Basic", Convert.ToBase64String(
System.Text.ASCIIEncoding.ASCII.GetBytes(
$"login:password")));
var httpRequestMessage = new HttpRequestMessage();
httpRequestMessage.Method = HttpMethod.Post;
httpRequestMessage.RequestUri = new Uri("<company>atlassian.net/rest/api/2/issue/");
httpRequestMessage.Content = new StringContent(Newtonsoft.Json.JsonConvert.SerializeObject(submitForm), Encoding.UTF8, "application/json");
var response = httpClient.SendAsync(httpRequestMessage).Result;
string responseBody = await response.Content.ReadAsStringAsync();
var jiraResponse = JsonConvert.DeserializeObject<TicketResponseBody>(responseBody);
TempData["Message"] = "Ticked Created";
TempData["Id"] = jiraResponse.Id;
TempData["Key"] = jiraResponse.Key;
TempData["Self"] = jiraResponse.Self;
return RedirectToAction("Index", "Home");
}
}
[HttpGet]
public async Task<ActionResult> GetUserToAssign()
{
using (var httpClient = new HttpClient())
{
var formatters = new List<MediaTypeFormatter>() {
new JsonMediaTypeFormatter(),
new XmlMediaTypeFormatter()
};
httpClient.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue(
"Basic", Convert.ToBase64String(
System.Text.ASCIIEncoding.ASCII.GetBytes(
$"login:password")));
var httpRequestMessage = new HttpRequestMessage();
httpRequestMessage.Method = HttpMethod.Get;
var content = await httpClient.GetAsync("<company>atlassian.net/rest/api/2/user/assignable/search?project=HOP");
string responseBody = await content.Content.ReadAsStringAsync();
var assigneBodyResponse = new List<AssigneeRequestBody>();
var allUsersFromJira = await content.Content.ReadAsAsync<IEnumerable<AssigneeRequestBody>>(formatters);
var resultsJira = allUsersFromJira.Cast<AssigneeRequestBody>().ToList();
return View();
}
Home Controller
public ActionResult Index(LogFilterModelVm filterModel)
{
if (filterModel == null || filterModel.ResultCount == 0)
{
filterModel = new LogFilterModelVm() { CurrentPage = 0, ResultCount = 50, FromDate = DateTime.Now.AddDays(-7), ToDate = DateTime.Now };
}
using (var repositoryCollection = new repositoryCollection())
{
var logsFromDb = repositoryCollection.ErrorLogsRepository.AllErrorLogs(filterModel.CurrentPage, filterModel.ResultCount, filterModel.Filter_Source, filterModel.Filter_Type, filterModel.Filter_User, filterModel.Filter_Host, filterModel.Filter_SearchBar, filterModel.FromDate , filterModel.ToDate);
var chartCount = new List<int>();
var chartNames = new List<string>();
foreach(var item in logsFromDb.ChartData)
{
chartCount.Add(item.Count);
chartNames.Add(item.Source);
}
var viewModel = new LogPackageVm()
{
ChartCount = chartCount,
ChartNames = chartNames,
LogItems = logsFromDb.LogItems,
FilterModel = new LogFilterModelVm(),
Distinct_SourceLog = logsFromDb.Distinct_SourceLog,
Distinct_TypeLog = logsFromDb.Distinct_TypeLog,
Distinct_UserLog = logsFromDb.Distinct_UserLog,
Distinct_HostLog = logsFromDb.Distinct_HostLog,
Filter_SearchBar = logsFromDb.Filter_SearchBar,
};
return View(viewModel);
}
}
I have tried to return Get results to View Model but I have failed.
Above picture shows what is my expected result
Thanks to user #codein I have manage to do this.
I have call the Method within my HomeController
var users = await new TicketController().GetUserToAssign();
Created a ViewBag with SelectList
ViewBag.Users = new SelectList(users, "accountId", "displayName");
And called it on my View
#Html.DropDownListFor(m => model.fields.assignee.name, (IEnumerable<SelectListItem>)ViewBag.Users)
That works great for me.
I have a mvc web application which contains chart and table data.
Scenario:
I am populating data in the Index method and return the model to view for binding. In view, table bind with the data. I also want to bind the chart with same data. Chart bind with child action. I set TempData[] object in the Index method and retrieve the same in Chart action.
Code:
Controller
public ActionResult Index()
{
var data = new List<MyModel>()
{
new MyModel { Text = "Name1", Value = 123 },
new MyModel { Text = "Name2", Value = 24 },
};
TempData["data"] = data;
return View(data);
}
public FileContentResult Chart()
{
List<MyModel> data = TempData["data"] as List<MyModel>;
var chart = new Chart
{
Width = 300,
Height = 450,
};
if (data != null)
{
chart.ChartAreas.Add("");
chart.Series.Add("");
chart.Series[0].ChartType = SeriesChartType.Column;
foreach (var q in data)
{
chart.Series[0].Points.AddXY(q.Text, Convert.ToDouble(q.Value));
}
}
using (var chartimage = new MemoryStream())
{
chart.SaveImage(chartimage, ChartImageFormat.Png);
return File(chartimage.GetBuffer(), #"image/png");
}
}
public async Task<ActionResult> Export()
{
var converter = new HtmlToPdf();
var baseAddress = new Uri("http://localhost:4545/");
var cookieContainer = new System.Net.CookieContainer();
using (var handler = new HttpClientHandler() { CookieContainer = cookieContainer })
using (HttpClient client = new HttpClient(handler) { BaseAddress = baseAddress })
{
var result = await client.GetAsync("/Home/Index");
var htmlString = await result.Content.ReadAsStringAsync();
var doc = converter.ConvertHtmlString(htmlString, baseAddress.ToString());
doc.Save(System.Web.HttpContext.Current.Response, true, "test.pdf");
doc.Close();
}
return null;
}
View:
<div class="row">
#using (Html.BeginForm("Index", "Home", FormMethod.Get))
{
<div class="col-md-12">
<table>
#{
foreach (var item in Model)
{
<tr>
<td>
#item.Text
</td>
<td>
#item.Value
</td>
</tr>
}
}
</table>
</div>
<div class="col-md-12">
<img src="#Url.Action("Chart")" />
<input type="submit" value="Filter" />
</div>
}
<div class="col-md-12">
#using (Html.BeginForm("Export", "Home", FormMethod.Post))
{
<input type="submit" value="Export" />
}
</div>
Problem:
Here i am using SelectPdf to export the web page to pdf. When i click Export button, it takes the content of web page so that again Index and Chart rendered. But here i didn't get tempdata[] values. It shows as null. So chart data not getting in pdf
Please help me to solve this issue
Please Note :
TempData in ASP.NET MVC can be used to store temporary data which can be used in the subsequent request. TempData will be cleared out after the completion of a subsequent request.
So to retain the values of TempData in subsequent request you need to call either TempData.Keep() or Peek("tempdata name").
Keep Syntax:
String data = TempData["myData"] as string;
TempData.Keep();
Peek Syntax:
String data = TempData.Peek("myData");
Try this
List<MyModel> data = (List<MyModel>)TempData.Peek("data");
I have many to many relationship in edit page how can i show selected items selected in a Dropdown multi select
here is my code:
// GET: Project/Edit/5
public ActionResult Edit(int? id)
{
if (id == null)
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
var edata = db.Projects.Find(id);
//check if data
if (edata == null)
return HttpNotFound();
//IEnumerable<SelectListItem> items = db.Provinces.Select(c => new SelectListItem { Value = c.ID.ToString(), Text = c.Name });
//ViewBag.ProvinceId = items;
//---Get all provice-----
var Prov = from c in db.Provinces select c;
//------get province ids---------------
var prov_id = from o in db.ProRel where o.ProjectId == id select o.ProvinceIds;
List<int> mid_list = new List<int>();
foreach (var p_ids in prov_id)
{
mid_list.Add(p_ids);
}
var option_vals = "";
var selected = string.Empty;
foreach (var p_itmes in Prov)
{
if (mid_list.Contains(p_itmes.ID))
{
selected = "selected='selected'";
}
else
{
selected = "";
}
option_vals += "<option "+selected+" value="+p_itmes.ID+">"+p_itmes.Name+"</option>";
}
string test = option_vals.ToString();
string test2 = test.Replace("\"", "");
ViewBag.options = test2;
return View(edata);
}
in my edit view my code:
<div class="form-group">
<label class="control-label col-md-2">Provinces</label>
<div class="col-md-10">
<select name="prov" id="prov">
#ViewBag.options
</select>
</div>
</div>
it displays the option values with double quotes at the end and it does not render like Html select options how can I remove the quotes that my options should be shown in its normal mode.
when I inspect element in browser the options are shown like this:
"<option value=1>Kabul</option><option selected='selected' value=2>Mazar</option><option selected='selected' value=3>Parwan</option><option value=4>Herat</option><option value=5>Badakhshan</option><option value=6>Takhar</option><option value=7>Smanagan</option><option selected='selected' value=8>Zabul</option>"
or you suggest me another way for this I am new to ASP.Net
I agree with #ChrFin Answer but with some more details which I hope will solve your problem
// GET: Project/Edit/5
public ActionResult Edit(int? id)
{
if (id == null)
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
var edata = db.Projects.Find(id);
//check if data
if (edata == null)
return HttpNotFound();
//IEnumerable<SelectListItem> items = db.Provinces.Select(c => new SelectListItem { Value = c.ID.ToString(), Text = c.Name });
//ViewBag.ProvinceId = items;
//---Get all provice-----
var Prov = from c in db.Provinces select c;
//------get province ids---------------
var prov_id = from o in db.ProRel where o.ProjectId == id select o.ProvinceIds;
List<int> mid_list = new List<int>();
foreach (var p_ids in prov_id)
{
mid_list.Add(p_ids);
}
var options = new List<SelectListItem>();
foreach (var p_itmes in Prov)
{
var item = new SelectListItem();
if (mid_list.Contains(p_itmes.ID))
item.Selected = true;
item.Value = p_itmes.ID.ToString();
item.Text = p_itmes.Name;
options.Add(item);
}
ViewBag.options = options;
return View(edata);
}
and inside your view add the following extra attribute:
<div class="form-group">
<label class="control-label col-md-2">Provinces</label>
<div class="col-md-10">
#Html.DropDownList("prov", (List<SelectListItem>)ViewBag.options, htmlAttributes: new { #class = "form-control", #multiple = "multiple" })
</div>
</div>
Short answer was already given by Marcos via his comment, but in general thats not how you create a select tag within MVC 5:
Controller:
public ActionResult Edit(int? id)
{
// other code
var options = new List<SelectListItem>();
foreach (var p_itmes in Prov)
{
var item = new SelectListItem();
if (mid_list.Contains(p_itmes.ID))
item.Selected = true;
item.Value = p_itmes.ID.ToString();
item.Text = p_itmes.Name;
options.Add(item);
}
ViewBag.options = options;
return View(edata);
}
View:
<div class="form-group">
<label class="control-label col-md-2">Provinces</label>
<div class="col-md-10">
#Html.DropDownList("prov", (List<SelectListItem>)ViewBag.options,
htmlAttributes: new { multiple = "multiple" })
</div>
</div>