retrieve back image from sql server database and display in MVC3 - asp.net-mvc-3

i stored few images in database in binary format, now i want to display those images in my view,how can we convert those images from binary format to image format again?
this is my action menthod in my controller
public ActionResult DislpayAllImage()
{
DataSet dsa = new DataSet();
dsa = objImage.getAllImages();
DataTable dt = new DataTable();
dt = dsa.Tables[0];
if (dt != null)
{
for (int i = 0; i < dt.Rows.Count; i++)
{
Byte[] image = (Byte[])dt.Rows[i]["UsImage"];
return File(image, "image/jpg");
}
}
return View();
}
this is my code in model
public DataSet getUserImage(int Id)
{
DataSet ds = new DataSet();
try
{
DbCommand db = dbcon.GetStoredProcCommand("GetImage");
dbcon.AddInParameter(db, "#Id", DbType.Int16, Id);
db.CommandType = CommandType.StoredProcedure;
return ds = dbconstr.ExecuteDataSet(dbCmd);
}
catch(Exception ex)
{
return ds = null;
}
}
view
#foreach( var image in ViewData.Images )
{
<img src="#Url.Action("DislpayImage", "Home",new { id = image.ImageID })" />
}
how can i display my image in razor view,also is the above code fine?

You need to call your Controller's Action(DislpayImage()) from the View like this:
<img src="<%= Url.Action("DislpayImage", "Controller") %>" alt="myimage" />
or
<img src="#Url.Action("DislpayImage", "Controller")" alt="myimage" />
Hope it helps you.
Edit
Just pass the id of the image you want to display to Controller action
public ActionResult DislpayImage(int id)
{
DataSet dsa = new DataSet();
dsa = objImage.getUserImage(id);
var imagedata = dsa.Tables[0].Columns["MyImage"];
return File(imagedata, "image/jpg");
}
Now pass the id of image which you want to display in your view, like this:
<img src="#Url.Action("DislpayImage", "Controller", new { id="2" })" alt="myimage" />
Now you will get the image with id as 2.

<% foreach( var image in ViewData.Images ) { %>
<%= Html.Image( Url.Action( "Show", "Image", new { id = image.ImageID } ) ) %>
<% } %>
public class ImageController : Controller
{
public void Show(string id)
{
Image image = GetImage(id);
Response.Buffer = True;
Response.Clear();
Response.ContentType = "image/gif";
Response.BinaryWrite( image.Data );
Response.End();
}
}
This response is just a copy of an answer from another forum.
This is not my own. I'm pasting it here to help you and someone else in this forum
with the same issue.
Here is the main link: http://forums.asp.net/post/2264885.aspx

Related

Posting dynamic table using ASP.NET Core MVC

I'm reading data from new tables using a SQL returning a datatable and able to show it in a view using the datatable as a model but the post/submit does not return anything, except in the HttpContext.Request.Form.
The new table column names cannot be determined except using SQL, so cannot use a model
// GET: /Home/
public async Task<IActionResult> Edit()
{
var conn = _context.Database.GetDbConnection();
await conn.OpenAsync();
var command = conn.CreateCommand();
command.CommandText = "SELECT * FROM NewTable";
var reader = await command.ExecuteReaderAsync();
DataTable dt = new DataTable();
dt.Load(reader);
dt.PrimaryKey = new DataColumn[]
{
dt.Columns["id"],
dt.Columns["idd"],
dt.Columns["idf"]
};
return View(dt);
}
#using System.Data
#model DataTable
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Edit</title>
</head>
<body>
<form asp-controller="Dynam" asp-action="Edit" method="post">
<table>
<tr>
#foreach (System.Data.DataColumn column in Model.Columns)
{
<td>#column.ColumnName</td>
}
</tr>
#for (var i = 0; i < Model.Rows.Count; i++)
{
var row = Model.Rows[i];
<tr>
#foreach (System.Data.DataColumn column in Model.Columns)
{
if (column.ColumnName == "id")
{
#Html.Hidden(column.ColumnName, row[column.ColumnName] )
}
else
{
<td>#Html.TextBox(column.ColumnName + "[" + i.ToString() + "]", row[column.ColumnName])</td>
}
}
</tr>
}
</table>
<div class="form-group">
<button type="submit" value="save" class="btn btn-default">Submit</button>
</div>
</form>
<div></div>
</body>
</html>
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(DataTable dt)
{
var commandText = "UPDATE MyTable SET #NewColumn = ('123xyz') " +
"WHERE Id = #Id AND Idd = #Idd AND Idf = #IDF";
var first = true;
foreach (string key in HttpContext.Request.Form.Keys)
{
// build sql for update
For example I create a model like this
using System.Collections.Generic;
namespace WebMvcApp.Models
{
public class DynamicTable
{
public string name { get; set; }
public List<Dictionary<string, string>> properties { get; set; }
}
}
I set all the rows as a List and all of the Column as a Dictionary. Then I create a test data like this:
public IActionResult Index()
{
var map1 = new Dictionary<string, string> {
{ "key1", "valueA1" },
{ "key2", "valueA2" },
{ "key3", "valueA3" }
};
var map2 = new Dictionary<string, string> {
{ "key1", "valueB1" },
{ "key2", "valueB2" },
{ "key3", "valueB3" }
};
var table = new List<Dictionary<string, string>>
{
map1,
map2
};
var entity = new DynamicTable
{
name = "table1",
properties = table
};
return View(entity);
}
Then I can deal with it in my view like this:
#model DynamicTable
<table>
<tr>
#foreach (var entry in Model.properties[0])
{
<td>#entry.Key</td>
}
</tr>
#{
foreach (var item in Model.properties)
{
<tr>
#foreach(var keypair in item)
{
<td>#keypair.Value</td>
}
</tr>
}
}
</table>

MVC: Load DropDown From <List>

Trying to load a Drop down and I am getting this error in my view:
Value cannot be null or empty.
Parameter name: name
This is the Controller
static List<AccountList> _acc = new List<AccountList>();
public ActionResult Index()
{
_acc = GetAccounts();
return View(_acc);
}
private List<AccountList> GetAccounts()
{
List<AccountList> temp = new List<AccountList>();
string sSource = "Test";
string sClinicId = "4";
string sStatus = null;
//This is simply retrieving the class from the web service where the list data is stored
ReconUIDataLayer.ClinicAccts retClinicAccts = new ReconUIDataLayer.ClinicAccts();
retClinicAccts = ReconUIDataLayer.UIDataLayer.LoadAccountInfo(sSource, sClinicId, ref sStatus);
temp = (from rows in retClinicAccts.ClinicAccts
select new AccountList
{
Text = rows.AcctName.ToString(),
Value = rows.AcctName.ToString(),
}).ToList();
return temp;
}
This is the View:
#model IEnumerable<C1MvcWebApplication3.Models.AccountList>
#using C1MvcWebApplication3.Models
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<div>
<table>
<tr><td>#Html.DropDownList("", new SelectList(Model.Select(x => new { Value = x, Text = x}),"AcctName","AcctName"))</td></tr>
</table>
</div>
</body>
</html>
The error is occurring on the helper to create the drop down.
I actually did two things to fix this:
1) just moved the List into my Controller
public ActionResult Index()
{
List<AccountList> _acc = new List<AccountList>();
_acc = GetAccounts();
return View(_acc);
}
I somehow think I didn't need to move the List declaration into the ActionResult and it may bite me later by not making it static.
2) Changed the call in my View
#Html.DropDownList("AccountList",new SelectList(Model, "Value", "Text"),"-Select")
Controller Code
readonly DBDashboardEntities DB = new DBDashboardEntities();// DB Entity Object
public ActionResult Index()
{
//using viewdata
ViewData["SelectDropDown_List"] =new SelectList(DB.tblStudents.ToList(), "studID", "studName");
//using viewbag
ViewBag.SelectDropDownList = new SelectList(DB.tblStudents.ToList(), "studID", "studName");
return View();
}
View Page code: index.cshtml
<tr>
<td>
#Html.DropDownListFor(c => c.studName, new SelectList(
new List<Object>{
new { value = 0 , text = "Rose" },
new { value = 1 , text = "John" },
new { value = 2 , text = "Smith"}
},
"value",
"text", 2))
</td>
<td>
#Html.DropDownListFor(c => c.studID, ViewData["SelectDropDown_List"] as SelectList) #*ViewData requires type casting*#
</td>
<td>
#Html.DropDownList("SelectDropDownList") #*String must be same as ViewBag.SelectDropDownList*#
</td>
</tr>

how can i get dropdownlist id in controller when we select an item using mvc4

I have dropdownlst which i have filled from database. Now i need to get the selected value in Controller do some manipulation. But null data will get. Code which i have tried.
##View##
#using (Html.BeginForm()) {
#Html.DropDownList("SupplierId", ViewBag.PurSupName as SelectList, new {#class = "form-control",style = "width: 200px;",id="supId"})
}
## Controller ##
public ActionResult ItemPurchased()
{
POS_DBEntities2 db = new POS_DBEntities2();
var query = from i in db.TBL_Account
where i.Type == "supplier"
select i;
ViewBag.PurSupName = new SelectList(query, "AccountId", "AccountName");
return PartialView("ItemPurchased", new List<PurchasedItem>());
}
##Controller##
public ActionResult GetPurchasedItem()
{
var optionsValue = this.Request.Form.Get("SupplierId");
return View();
}
You can try with below changes.
#using (Html.BeginForm("GetPurchasedItem","YourController")) {
#Html.DropDownList("SupplierId", ViewBag.PurSupName as SelectList, new {#class = "form-control",style = "width: 200px;",id="supId"})
<input type="submit" value="OK" />
}
Controller will be
[HttpPost]
public ActionResult GetPurchasedItem(string SupplierId)
{
var optionsValue = SupplierId;
//..............
return View();
}
It should work normally..

ASP.NET MVC AjaxActionLink

My partialview didnot load, i'm using AjaxActionLink
here is my view where i call my partialview
#foreach (var p in Model.Rooms)
{
<div class="room">
<h3>#p.RoomTitle</h3>
<img src="#p.PhotoRoom" alt="room"/>
<h4>#p.TitlePrice</h4>
<blockquote>#p.Description</blockquote>
#Ajax.ActionLink("Order room", "PartialDetail", new { #p.RoomID }, new AjaxOptions { UpdateTargetId = "results", LoadingElementId = "loading",HttpMethod = "POST",InsertionMode = InsertionMode.InsertAfter})
</div>
}
Here is my controller
public PartialViewResult PartialDetail(int roomid)
{
Room rooms =
repository.Room.FirstOrDefault(p => p.RoomID == roomid);
var viewModel = new RoomEditViewModel
{
RoomID = rooms.RoomID,
RoomTitle = rooms.RoomTitle,
Description = rooms.Description,
PhotoRoom = rooms.PhotoRoom
};
ViewBag.room = roomid;
return PartialView(viewModel);
}
fixed your ajax action link
What you set
#Ajax.ActionLink("Order room", "PartialDetail", new { #p.RoomID }
Should be
#Ajax.ActionLink("Order room", "PartialDetail", new { roomid = #p.RoomID }
As a recommendation set the aceepted protocols in your action
[HttpPost]
public PartialViewResult PartialDetail(int roomid)

Jquery dynamic load dropdownlist

I have a problem about dynamic load dropdownlist. I debuged my ashx, it do post the data. But dropdownlist have no value.
Here is my Aspx page
<script type="text/javascript">
$(function() {
$.post("ContentLoad.ashx", function(datas) {
for(var i = 0; i < datas.length; i++) {
var data = datas[i];
var option = $("<option value='"+data.Id + "'>" +data.Title + "</option");
$("#ddlClassId").append(option);
}
},"json");
});
</script>
In the html have a dropdownlist.
<asp:DropDownList ID="ddlClassId" runat="server" AutoPostBack="True">
</asp:DropDownList>
And here is my ashx code:
public class ContentLoad : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
BLL.ChannelManeger bll = new BLL.ChannelManeger();
DataTable dt = bll.GetList(0, 0);
Data[] datas = new Data[dt.Rows.Count];
int i = 0;
foreach (DataRow dr in dt.Rows)
{
string id = dr["Id"].ToString();
int ClassLayer = int.Parse(dr["ClassLayer"].ToString());
string title = dr["Title"].ToString().Trim();
if (ClassLayer == 1)
{
datas[i++] = new Data() { Id = Convert.ToInt32(id), Title = title };
}
else
{
title = "├ " + title;
title = StringOfChar(ClassLayer - 1, " ") + title;
datas[i++] = new Data() { Id = Convert.ToInt32(id), Title = title };
}
}
JavaScriptSerializer serializer = new JavaScriptSerializer();
context.Response.Write(serializer.Serialize(datas));
}
public static string StringOfChar(int strLong, string str)
{
string ReturnStr = "";
for (int i = 0; i < strLong; i++)
{
ReturnStr += str;
}
return ReturnStr;
}
public bool IsReusable
{
get
{
return false;
}
}
}
class Data
{
public int Id { get; set; }
public string Title { get; set; }
}
In your code there was a typo inside for loop and also since dropdown list is a server control, its id might change so you should not use id selector unless you use ClientID of the control. I have simplied your code using $.each loop take a look.
$(function() {
$.post("ContentLoad.ashx", function(datas) {
var $ddl = $("select[id*=ddlClassId]");
$.each(datas, function(){
$ddl.append("<option value='"+this.Id + "'>" +this.Title + "</option");
});
},"json");
});
look at this line: var data = data[i];
it should be var data = datas[i];

Resources