I am trying to display an image stored in the database (actually a varbinary) and trying to display it in a "img" tag. Simple View:
<table style="font-size:x-small">
#Html.HiddenFor(x=>x.CandidateId, new { #id = "txtCandidateId"})
<tr>
<td>
#Html.DisplayNameFor(x=>x.Name)
</td>
<td>
#Html.DisplayTextFor(x=>x.Name)
</td>
<td>
AD Account User Name:
</td>
<td>
<input type="text" id="txtUsername" />
</td>
</tr>
<tr>
<td colspan="4">
<img id="img" src="" alt="" />
</td>
</tr>
</table>
Then in script:
var cand;
$(document).ready(function () {
debugger;
cand = function () { return #Html.Raw(Json.Encode(Model)) }();
var source = "/InProcess/RetrieveImage/" + cand.CandidateId;
$("#img").attr("src", source);
});
Then in controller:
public ActionResult RetrieveImage(string candidate)
{
byte[] pdf;
using (var memStream = new MemoryStream())
{
Repository.GetCandidatePdf(candidate).CopyTo(memStream);
pdf = memStream.ToArray();
}
if (pdf != null)
{
return File(pdf, "cover/jpg");
}
else
return null;
}
I can see the correct id, which is a uniqueidentifer, in the JS of the page and the action is getting called but the candidateId is null. Anybody have any ideas why? Is there a better way to do this?
By default, the route parameters in ASP.NET MVC are {controller}, {action}, and {id} - controller and action are handled for you, and id needs to be the name of the action paramemter:
public ActionResult RetrieveImage(String id) {
...
}
Also your Content-Type is incorrect, it should be image/jpeg if you're returning a JPEG image, or application/pdf if you're returning an Adobe PDF document. However you cannot load a PDF into an <img /> element.
Related
I created a controller and a view, to fetch data from my database an image, which is in blob format. However, the image is not loaded in the view (I call a method to call this view).
I have the controller Image (with the GetImage method), the ReadyDrive controller and the ReadyDelivery view. Within the ReadyDate view, I pass the parameter to get the ID in the GetImage method.
Controller Imagem:
public ActionResult Index()
{
return View();
}
public ActionResult GetImagem(int id)
{
Entities1 tabela = new Entities1();
byte[] BlobImg = tabela.DATABINARY.Where(p => p.ID.Equals(id)).Select(p => p.DATA).FirstOrDefault();
return File(BlobImg, "image/png");
}
Controller ProntaEntrega:
public ActionResult Index(int? reduzido=null)
{
Entities1 Estoque = new Entities1();
List<V500_ESTOQUE_PE_WEB> ProntaE = (from a in Estoque.V500_ESTOQUE_PE_WEB select a).OrderByDescending(x => x.TOTAL_KG_PE).ToList()
.Where(x => reduzido != null ? x.COD_REDUZIDO.Equals(reduzido) : true).ToList();
return View(ProntaE);
}
View ProntaEntrega (a piece of that):
<tbody>
#foreach (var item in Model)
{
<tr>
<td class="text-left" width="30%">
#Html.DisplayFor(d => item.COD_REDUZIDO)
</td>
<td class="text-left">
#Html.DisplayFor(d => item.DESC_ARTIGO)
</td>
<td class="text-right">
#Html.DisplayFor(d => item.TOTAL_KG_PE)
</td>
<td>
<img src="#Url.Action("GetImage", "Imagem", new { id = #item.IDBLOB})" width=50 />
</td>
</tr>
}
</tbody>
Somebody to help me?
Tks!
convert the blob in base64. set image src something like below
<img src="data:image/jpeg;base64,iVBORw0KGg" />
reference
I have created a form which to insert few data into database. I am using jquery to insert the data in my mvc project but I am getting confused in how can I create insert function.
First thing, I have created a one method to Insert or Updating the record via ID. But I don't know how can I use Id as primary to check whether to Insert or Update. I know that if my ID is equal to 0 means Insert or if greater than 0 then update but how can I add that into my function. Second, I know my Insert function does not seems to be right way but what could be easier way to implement?
(View).asmx
<script type="text/javascript">
$(document).ready(function() {
//function will be called on button click having id btnsave
$("#btnRoleListSubmit").click(function() {
$.ajax({
type: "POST", //HTTP POST Method
url: '/Admin.mvc/Admin/InsertRoleList', // Controller/View
data: { //Passing data
Name: $("#Name").val(), //Reading text box values using Jquery
Role: $("#Role").val(),
}
});
});
});
</script>
<table align="center">
<tr>
<td valign="top" width="100" class="col-label">
<span>Name</span>
</td>
<td class="col-label">
<input type="text" maxlength="200" style="margin-left: 0;" name="Name" id="Name"
class="required" value="" />
</td>
</tr>
<tr>
<td valign="top" class="col-label">
Employee Role
</td>
<td class="col-label">
<textarea id="Role" name="Role" class="required" cols="15" rows="2"></textarea>
</td>
</tr>
</table>
<hr />
<div style="margin: 12px;" align="center">
<button type="submit" name="btnRoleListSubmit" class="actionButton">
<span>Add Employee Role</span></button>
</div>
(Controller).cs
public ActionResult InsertRoleList(int branchId, RoleListViewModel obj)
{
AddDetails(branchId, obj);
return View();
}
private void AddDetails(int branchId, EmailListViewModel obj)
{
Branch branches = this._branches.GetID(branchId);
var GetDB = branches.GetClientDatabase();
RoleListViewModel listData = new RoleListViewModel();
{
listData.Name= obj.Name;
listData.Role= obj.Role;
};
List<int> lstIds = GetDB.InsertorUpadateRole(obj);
}
SqlQueries.cs
public List<int> InsertorUpadateRole (RoleList obj)
{
RoleList lstData = new RoleList();
string sqlQuery = string.Empty;
sqlQuery = #"INSERT INTO [dbo].[EmployeeRoleList]
([name],
[is_active],
[role],
[is_admin]
}
VALUES ( '{0}','1','{2}','0')
SELECT SCOPE_IDENTITY() AS id;";
try
{
this.ExecuteReader((record) =>
{
Name = Convert.ToInt32(record["name"]);
Role = Convert.ToInt32(record["role"]);
},
string.Format(sqlQuery, lstdata.Name, lstdata.Role));
}
catch (Exception e)
{
var message = e;
}
}
Can anyone help with this?
Your url usually starts with the controller, try "/Admin/InsertRoleList". Your ajax post parameters need to match the controller InsertRoleList(string Name, string Role) which is not very similar to your controller code...
I got this error when I am trying to remove the item from the Cart table.
HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable. Please review the following URL and make sure that it is spelled correctly.
Requested URL: /Panier/RemoveFromCart/1. This URL seems to be fine with me. It should branch to the PanierController at RemoveCart. I don't understand why it is not branching.
Thanks
Index.cshtml
#model Tp1WebStore3.ViewModels.ShoppingCartViewModel
#{
ViewBag.Title = "Shopping Cart";
}
<script src="/Scripts/jquery-1.4.4.min.js"
type="text/javascript"></script>
<script type="text/javascript">
$(function () {
// Document.ready -> link up remove event handler
$(".RemoveLink").click(function () {
// Get the id from the link
var recordToDelete = $(this).attr("data-id");
if (recordToDelete != '') {
// Perform the ajax post
$.post("/ShoppingCart/RemoveFromCart", {"id": recordToDelete },
function (data) {
// Successful requests get here
// Update the page elements
if (data.ItemCount == 0) {
$('#row-' + data.DeleteId).fadeOut('slow');
} else {
$('#item-count-' + data.DeleteId).text(data.ItemCount);
}
$('#cart-total').text(data.CartTotal);
$('#update-message').text(data.Message);
$('#cart-status').text('Cart (' + data.CartCount + ')');
});
}
});
});
</script>
<h3>
<em>Details</em> du panier:
</h3>
<p class="button">
#Html.ActionLink("Checkout >>", "AddressAndPayment", "Checkout")
</p>
<div id="update-message">
</div>
<table>
<tr>
<th>
Produit
</th>
<th>
Prix (unitaire)
</th>
<th>
Quantite
</th>
<th></th>
</tr>
#foreach (var item in Model.CartItems)
{
<tr id="row-#item.ProduitId">
<td>
#Html.ActionLink(item.Produit.Description,"Details", "Store", new { id =
item.ProduitId }, null)
</td>
<td>
#item.Produit.Prix
</td>
<td id="item-count-#item.ProduitId">
#item.Quantite
</td>
<td>
#Html.ActionLink("Enlever du panier", "RemoveFromCart", "Panier", new { id =
item.ProduitId }, null)
</td>
</tr>
}
<tr>
<td>
Total
</td>
<td></td>
<td></td>
<td id="cart-total">
#Model.CartTotal
</td>
</tr>
</table>
PanierController.cs
namespace Tp1WebStore3.Controllers
{
public class PanierController : Controller
{
Tp1WebStoreDBEntities dbProduit = new Tp1WebStoreDBEntities();
[HttpPost]
public ActionResult RemoveFromCart(int id)
{
// Remove the item from the cart
var cart = ShoppingCart.GetCart(this.HttpContext);
// Get the name of the product to display confirmation
string produitDescription = dbProduit.Paniers
.Single(item => item.PanierId == id).Produit.Description;
// Remove from cart
int itemCount = cart.RemoveFromCart(id);
// Display the confirmation message
var results = new ShoppingCartRemoveViewModel
{
Message = Server.HtmlEncode(produitDescription) +
" has been removed from your shopping cart.",
CartTotal = cart.GetTotal(),
CartCount = cart.GetCount(),
ItemCount = itemCount,
DeleteId = id
};
return View("Details");
}
Your RemoveFromCart controller action is decorated with the [HttpPost] attribute meaning that it is ONLY accessible by POST verbs. But in your view you seem to have generated some action link to it:
#Html.ActionLink(
"Enlever du panier",
"RemoveFromCart",
"Panier",
new { id = item.ProduitId },
null
)
But as you are well aware, an Html.ActionLink translates into an <a> tag in your markup which obviously is sending a GET request to the server when clicked.
So basically you have 3 possibilities here:
Use an Html.BeginForm instead of an ActionLink to refer to this action which would allow you to send a POST request
Get rid of the [HttpPost] attribute from your RemoveFromCart action
AJAXify the anchor which would allow you to use a POST request.
My code works perfectly in VS2010 C# but once published to IIS7 the PartialView (list of records) does not get rendered in the View...it rolls to a new page without the data except for the correct record count retrieved from SQL server. SQL server is on separate box.
I have searched for hours on this site with no luck finding a resolution.
View with the RenderPartial:
<table style="width:100%">
<tr>
<td>
<h3>Outage Tracking List (Open or Active)</h3>
</td>
<td style="text-align:right">
<h1><%: ViewData["ApplicationName"]%></h1>
</td>
</tr>
</table>
<% Html.RenderPartial("OutageSearch",this.ViewData.Model); %>
PartialView:
<%# Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<OutageTrackingWebSite.Models.OutageViewModel" %>
<div>
<script language="javascript" type="text/javascript">
function OutageSearch() {
$("#OutageSearchForm #CurrentPageNumber").val("1");
PostSearchForm();
}
Various functions then the rest of the partialview
<% using (Ajax.BeginForm("OutageSearch", null,
new AjaxOptions { UpdateTargetId = "DivOutageSearchResults", OnComplete="OutageSearchComplete" },
new { id = "OutageSearchForm" })) { %>
<table style="background-color: #ebeff2; width: 100%; border:solid 1px #9fb8e9" cellspacing="2" cellpadding="2">
<tr>
<td style="width: 60%; text-align: left">
<input id="btnSearch" onclick="OutageSearch();" type="submit" value="List Open/Active" />
</td>
</tr>
</table>
<div id="DivOutageSearchResults">
<% Html.RenderPartial("OutageSearchResults", this.ViewData.Model); %>
</div>
<% } %>
additional PartialView
<%# Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<%OutageTrackingWebSite.Models.OutageViewModel" >
<input name="CurrentPageNumber" type="hidden" id="CurrentPageNumber" value="<%=Model.CurrentPageNumber%>" />
<input name="TotalPages" type="hidden" id="TotalPages" value="<%=Model.TotalPages%>" />
<input name="SortBy" type="hidden" id="SortBy" value="<%=Model.SortBy%>" />
<input name="SortAscendingDescending" type="hidden" id="SortAscendingDescending" value="<%=Model.SortAscendingDescending%>" />
<input name="PageSize" type="hidden" id="PageSize" value="9" />
<script language="javascript" type="text/javascript">
function GetOutageDetails(OutageID) {
if (formIsDisabled == false) {
DisableForm();
formData = "OutageID=" + OutageID;
setTimeout(PostOutageIDToServer, 1000);
}
}
function PostOutageIDToServer() {
$.post("/Outage/GetOutageInformation", formData, function (data, textStatus) {
OutageUpdateComplete(data);
}, "json");
}
Controller
public ActionResult DisplayOutageList()
{
Models.OutageViewModel outageViewModel = new Models.OutageViewModel();
outageViewModel.TotalPages = 0;
outageViewModel.TotalRows = 0;
outageViewModel.CurrentPageNumber = 0;
ViewData.Model = outageViewModel;
string applicationName = Convert.ToString( System.Configuration.ConfigurationManager.AppSettings["ApplicationName"]);
ViewData["ApplicationName"] = applicationName;
return View("OutageMaintenance");
}
///
/// Outage Search
///
///
public PartialViewResult OutageSearch()
{
long totalRows;
long totalPages;
bool returnStatus;
string returnErrorMessage;
OutageBLL OutageBLL = new OutageBLL();
Models.OutageViewModel outageViewModel = new Models.OutageViewModel();
this.UpdateModel(outageViewModel);
List Outages = OutageBLL.OutageSearch(
outageViewModel,
outageViewModel.CurrentPageNumber,
outageViewModel.PageSize,
outageViewModel.SortBy,
outageViewModel.SortAscendingDescending,
out totalRows,
out totalPages,
out returnStatus,
out returnErrorMessage);
ViewData["Outages"] = Outages;
outageViewModel.TotalPages = totalPages;
outageViewModel.TotalRows = totalRows;
ViewData.Model = outageViewModel;
return PartialView("OutageSearchResults");
}
///
/// Get Outage Information
///
///
public JsonResult GetOutageInformation()
{
bool returnStatus;
string returnErrorMessage;
List returnMessage;
OutageBLL outageBLL = new OutageBLL();
Models.OutageViewModel outageViewModel = new Models.OutageViewModel();
this.TryUpdateModel(outageViewModel);
Outage outage = outageBLL.GetOutageInformation(
outageViewModel.OutageID,
out returnStatus,
out returnErrorMessage,
out returnMessage);
outageViewModel.UpdateViewModel(outage, typeof(Outage).GetProperties());
outageViewModel.ReturnMessage = returnMessage;
outageViewModel.ReturnStatus = returnStatus;
outageViewModel.OutageScheduledDate = UtilitiesBLL.FormatDate(outageViewModel.ScheduledDate);
outageViewModel.OutagePlannedDuration = UtilitiesBLL.FormatDuration(outageViewModel.PlannedDuration);
return Json(outageViewModel);
}
Check your included JavaScript files on the deployed version. If you are missing some files (MicrosoftMvcAjax.js, jQuery.js), the page could simply be posting instead of using an Ajax post.
So I have this HTML page that is exported to an Excel file through an MVC action. The action actually goes and renders this partial view, and then exports that rendered view with correct formatting to an Excel file. However, the view is rendered exactly how it is seen before I do the export, and that view contains an "Export to Excel" button, so when I export this, the button image appears as a red X in the top left corner of the Excel file.
I can intercept the string containing this HTML to render in the ExcelExport action, and it looks like this for one example:
<div id="summaryInformation" >
<img id="ExportToExcel" style=" cursor: pointer;" src="/Extranet/img/btn_user_export_excel_off.gif" />
<table class="resultsGrid" cellpadding="2" cellspacing="0">
<tr>
<td id="NicknameLabel" class="resultsCell">Nick Name</td>
<td id="NicknameValue" colspan="3">
Swap
</td>
</tr>
<tr>
<td id="EffectiveDateLabel" class="resultsCell">
<label for="EffectiveDate">Effective Date</label>
</td>
<td id="EffectiveDateValue" class="alignRight">
02-Mar-2011
</td>
<td id ="NotionalLabel" class="resultsCell">
<label for="Notional">Notional</label>
</td>
<td id="NotionalValue" class="alignRight">
<span>
USD
</span>
10,000,000.00
</td>
</tr>
<tr>
<td id="MaturityDateLabel" class="resultsCell">
<label for="MaturityDate">Maturity Date</label>
</td>
<td id="MaturityDateValue" class="alignRight">
02-Mar-2016
-
Modified Following
</td>
<td id="TimeStampLabel" class="resultsCell">
Rate Time Stamp
</td>
<td id="Timestamp" class="alignRight">
28-Feb-2011 16:00
</td>
</tr>
<tr >
<td id="HolidatCityLabel" class="resultsCell"> Holiday City</td>
<td id="ddlHolidayCity" colspan="3">
New York,
London
</td>
</tr>
</table>
</div>
<script>
$("#ExportToExcel").click(function () {
// ajax call to do the export
var actionUrl = "/Extranet/mvc/Indications.cfc/ExportToExcel";
var viewName = "/Extranet/Views/Indications/ResultsViews/SummaryInformation.aspx";
var fileName = 'SummaryInfo.xls';
GridExport(actionUrl, viewName, fileName);
});
</script>
That <img id="ExportToExcel" tag at the top is the one I want to remove just for the export. All of what you see is contained within a C# string. How would I go and remove that line from the string so it doesn't try and render the image in Excel?
EDIT: Would probably make sense also that we wouldn't need any of the <script> in the export either, but since that won't show up in Excel anyway I don't think that's a huge deal for now.
Remove all img tags:
string html2 = Regex.Replace( html, #"(<img\/?[^>]+>)", #"",
RegexOptions.IgnoreCase );
Include reference: using System.Text.RegularExpressions;
If it's in a C# string then just:
myHTMLString.Replace(#"<img id="ExportToExcel" style=" cursor: pointer;" src="/Extranet/img/btn_user_export_excel_off.gif" />","");
The safest way to do this will be to use the HTML Agility Pack to read in the HTML and then write code that removes the image node from the HTML.
HtmlDocument doc = new HtmlDocument();
doc.LoadHtml(htmlString);
HtmlNode image =doc.GetElementById("ExportToExcel"]);
image.Remove();
htmlString = doc.WriteTo();
You can use similar code to remove the script tag and other img tags.
I'm just using this
private string RemoveImages(string html)
{
StringBuilder retval = new StringBuilder();
using (StringReader reader = new StringReader(html))
{
string line = string.Empty;
do
{
line = reader.ReadLine();
if (line != null)
{
if (!line.StartsWith("<img"))
{
retval.Append(line);
}
}
} while (line != null);
}
return retval.ToString();
}