Problem with Image uploading to SQL - asp.net-mvc-2

I have problem with uploading image to SQL database.
i have Methods Upload in controller Upload
dbData userDb = new dbData();
public ActionResult Upload()
{
return View();
}
[HttpPost]
public ActionResult Upload(HttpPostedFileWrapper file)
{
if (file.ContentLength > 0)
{
Stream fileStream = file.InputStream;
string fileName = Path.GetFileName(file.FileName);
int fileLength = file.ContentLength;
byte[] fileData = new byte[fileLength];
fileStream.Read(fileData, 0, fileLength);
var image = new ImageTable();
image.Image = fileData;
image.Description = "Default profile picture";
try
{
userDb.ImageTables.InsertOnSubmit(image);
userDb.SubmitChanges();
return RedirectToAction("Success");
}
catch (Exception ex)
{
throw;
}
}
return View();
}
If i use this view page
<%# Page Language="C#" Inherits="System.Web.Mvc.ViewPage<dynamic>" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Upload</title>
</head>
<body>
<div>
<% using (Html.BeginForm("Upload", "Upload", FormMethod.Post, new { enctype = "multipart/form-data" }))
{%>
<input name="file" type="file" runat="server" id="file"/><br />
<input type="submit" value="Upload File" />
<%} %>
</div>
</body>
</html>
everithing works great but if i want to use view runned on masterpage i wil get this error after i click upload submit button:
No parameterless constructor defined for this object.
Know someone where is problem and how can i fix it ?
Thanks

This error occurs because default model binder can't create instances of classes that don't contain parameterless constructor (such as HttpPostedFileWrapper).
Simplest way around this is to just pull files from Request.Files (e.g. Request.Files["file"]).
Alternatively, you could create custom model binder for that.
UPDATE:
This is action method I used:
[HttpPost]
public ActionResult Index(FormCollection form)
{
var file = Request.Files["file"];
if(file != null && file.ContentLength > 0)
{
// ...
}
return View();
}

Related

odbcconnection in ADO.NET does not contain a definition for executereader

While creating ODBC reader in ADO.NET, as shown below:
//using bla bla bla
using System.Data.Odbc;
//some code
OdbcDataReader rdr = cmd.ExecuteReader();
//rest of the code
I get an error:
OdbcConnection does not contain a definition for 'ExecuteReader' and no extension method 'ExecuteReader' accepting a first argument of type 'OdbcConnection' could be found (are you missing a using directive or an assembly reference?
I am 100% sure I am missing no using directive nor assembly reference, I've added it myself, so why wouldn't it recognize the method?
Edit: full backend code and aspx code:
Backend C# code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Windows.Forms;
using System.Data.Odbc;
namespace WebApp1
{
public partial class Test : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
using (SqlConnection cnct = new SqlConnection("Server=x.x.x.x;User ID=xx;Password=xx;Database=xxxx;"))
{
try
{
cnct.Open();
using (SqlCommand cmd = new SqlCommand("select codcli from client", cnct))
{
SqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
string code = rdr.GetString(1);
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
}
}
ASPX page code:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Test.aspx.cs" Inherits="WebApp1.Test" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<table runat="server">
<asp:Repeater ID="repeater" runat="server">
<HeaderTemplate>
<tr class="Header">
<td>Code</td>
</tr>
</HeaderTemplate>
<ItemTemplate>
<tr>
<td>
<%# Eval("code") %>
</td>
</tr>
</ItemTemplate>
</asp:Repeater>
</table>
</body>
</html>
PS: I am sorry for not including the whole code from the beginning, as I am new to StackOverFlow, thank you for being patient with me

Usung ASP.NET MongoDB.Driver and I can't save ContextType

From the course: Using MongoDB with ASP.NET MVC
Demo: Displaying Rental Images
^In case you have Pluralsight
At this point in the course we had attached the images to a Rental document, next we use some razor and a GetImage Action to display an image on a AttachImage.cshtml view. I believe all of that works, the image is getting attached to the document in the database.
Q: When we save the image to the database, why is the ContentType not getting added to the fs.files collection (GridFS) in the database?
NOTE: I believe the code inside the controller that is culprit is at or around:
//------------------------------------------
var options = new MongoGridFSCreateOptions
{
Id = imageId,
ContentType = file.ContentType
};
//------------------------------------------
Proof the image got stored using GridFS
Proof ContentType Didn't get saved
AttachImage.cshtml
#model RealEstate.Rentals.Rental
#{ ViewBag.Title = "AttachImage"; }
<h4>Attach Rental Image</h4>
#using (Html.BeginForm(null, null, FormMethod.Post, new {enctype =
"multipart/form-data" }))
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<div class="form-group">
<label class="control-label col-md-2">Decription</label>
<div class="col-md-10">
#Model.Description
</div>
</div>
<div class="form-group">
#Html.Label("Image", new { #class = "control-label col-md-2" })
<div class="col-md-10">
<input type="file" name="file" id="file" />
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Attach" class="btn btn-default" />
</div>
</div>
</div>
}
#if (Model.HasImage())
//Show Image
{
<img src="#Url.Action("GetImage", new { id = Model.ImageId })" />
}
AttachImage Page in Browser
RentalsController.cs
namespace RealEstate.Controllers
{
public class RentalsController : Controller
{
public readonly RealEstateContext Context = new RealEstateContext();
public ActionResult Post()
{
return View();
}
[HttpPost]
public ActionResult Post(PostRental postRental)
{
var rental = new Rental(postRental);
Context.Rentals.Insert(rental);
return RedirectToAction("Index");
}
public ActionResult AttachImage(string id)
{
var rental = GetRental(id);
return View(rental);
}
[HttpPost]
public ActionResult AttachImage(string id, HttpPostedFileBase file)
{
var rental = GetRental(id);
if (rental.HasImage())
{
DeleteImage(rental);
}
StoreImage(file, rental);
return RedirectToAction("Index");
}
public ActionResult GetImage(string id)
{
var image = Context.Database.GridFS
.FindOneById(new ObjectId(id));
if (image == null)
{
return HttpNotFound();
}
return File(image.OpenRead(), image.ContentType);
}
private Rental GetRental(string id)
{
var rental = Context.Rentals.FindOneById(new ObjectId(id));
return rental;
}
private void DeleteImage(Rental rental)
{
//Access GrdFS & Delete By ID / Pass ImageID converted to ObjectId
Context.Database.GridFS.DeleteById(new ObjectId(rental.ImageId));
rental.ImageId = null;
Context.Rentals.Save(rental);
}
private void StoreImage(HttpPostedFileBase file, Rental rental)
{
var imageId = ObjectId.GenerateNewId();
rental.ImageId = imageId.ToString();
Context.Rentals.Save(rental);
var options = new MongoGridFSCreateOptions
{
Id = imageId,
ContentType = file.ContentType
};
Context.Database.GridFS.Upload(file.InputStream, file.FileName);
}
I don't know what else to do check, everything not only looks right from my perspective, but it's to the tee (As far as I can tell) from the Course Instruction..
pass the MongoGridFSCreateOptions options to the call to Upload as the last argument:
Context.Database.GridFS.Upload(file.InputStream, file.FileName, options);
Thankfully that's an easy enough fix :)

Display Text from DropDownListFor

Here's the view:
<%# Page Language="C#" Inherits="System.Web.Mvc.ViewPage<TravelDeskWebsite.Models.TestModel>" %>
<!DOCTYPE html>
<html>
<head>
<title>TestPage</title>
</head>
<body>
<% using (Html.BeginForm())
{ %>
<%= Html.DropDownListFor(x => x.SelectedText, ViewBag.Tests as SelectList)%>
<%: (string)ViewBag.Test %>
<% } %>
</body>
</html>
The controller:
public ActionResult TestFunc(TestModel model)
{
List<string> TestList = new List<string>();
TestList.Add("Help");
TestList.Add("Please");
ViewBag.Tests = new SelectList(TestList, model.SelectedText);
ViewBag.Test = model.SelectedText;
return View();
}
What I wanted to achieve here is just to display the selected value as text on the same view. The problem is that the ViewBag returns null even if I have a selected value. When I test it, it throws null exception.
You will have your SelectedValue in the SelectedText Property. try to use that.
ViewBag.Test = model.SelectedText;
return View(model);

Processing form's element(s) in JSP

I have a HTML form in JSP page, and in the I have a JavaScript validation. The user must enter one field: name or id or year, and a java file will search the student in database by name or by id or by year. The JavaScript alerts when no field is filled and performs the action if one field is filled.
<html>
<head>
<title>Student to search into database</title>
<script language="javascript">
function validate2(objForm){
int k = 0;
if(objForm.name.value.length==0){
objForm.name.focus();
k++;
}
if(objForm.year.value.length==0){
objForm.year.focus();
k++;
}
if(objForm.id.value.length==0){
objForm.year.focus();
k++;
}
if(k == 0){
return false;
}
return true;
}
</script>
</head>
<body bgcolor=#ADD8E6><center>
<form action="FoundStudents.jsp" method="post" name="entry2" onSubmit="validate2(this)">
<input type="hidden" value="list" name="seek_stud">
...........................................................................................
The problem is I want to process the parameter which I receive in FoundStudents.jsp: If I get the year, I look in DB which student(s) are in that year and display all that student(s)' data(do that in a java file). How could I do that in FoundStudents.Jsp without checking again which field is filled(I've done that in JavaScript from SearchStudent.jsp). I mean the FoundStudents.jsp calls a method in the java file for searching and displaying.
I tried by now with the input hidden that worked, but that is for more forms. I have only 1.
FoundStudent.jsp
<%#page import="stud.diploma.students.StudentsManager"%>
<%#page import="stud.diploma.students.Student"%>
<%#page import="java.util.ArrayList"%>
<%#page import="stud.diploma.database.ConnectionsManager"%>
<%# page language="java" import="java.sql.*, java.lang.*" %>
<%
Student search = null;
if(request.getParameter("seek_stud") != null){
//reading params from the SearchStudent form
String name = request.getParameter("name");
String year_prime = request.getParameter("year");
int year, id;
try{
year = Integer.parseInt(year_prime);
}catch(Exception e1){
year = 0;
}
String id_prime = request.getParameter("id");
try{
id = Integer.parseInt("id");
}catch(Exception e2){
id = 0;
}
if(name.length() != 0){
search = StudentsManager.getInstance().studByName(name);
}
if(year > 0){
search = StudentsManager.getInstance().studByYear(year);
}
if(id > 0){
search = StudentsManager.getInstance().studById(id);
}
if(search != null){
%>
<html>
<body bgcolor=#4AA02C>
<center>
<h2>Student's data</h2>
<table border="1" cellspacing="1" cellpadding="8" bgcolor= #EBDDE2>
<tr>
<td bgcolor= #FF9966><b>ID</b></td>
<td bgcolor= #FF9966><b>Name</b></td>
<td bgcolor= #FF9966><b>Year</b></td>
</tr>
<tr>
<td><%= search.getId()%></td>
<td><%= search.getName()%></td>
<td><%= search.getYear()%></td>
</tr>
</table>
</center>
</body>
</html>
<%}else{%>
<%
String redirectURL = "MainMenu.html";
response.sendRedirect(redirectURL);
%>
<%}%>
<%}%>
This FoundStudent.jsp is for the version of multiple forms (using hidden input) that worked. (the javascript test was just a little bit different, I typed it insted of what I had in the beginning)
It searched by name and by year only. Didn't search by ID (I had exception here <td><%= search.getId()%></td> I'm still trying to see how to deal with it. ID is a AUTO_INCREMENT PRIMARY KEY)
Lines like : search = StudentsManager.getInstance().studByName(name);
Search is a Student type object. (Object Student is creaded in a java file)
StudentsManager is a java class that receives calls to it's methods from JSP. getInstance() creates an instance of StudentsManager. Method studByName(name) receives the parameter name from the form and searches it in the database.
So I changed the (java)script to:
<script language="javascript">
function validateSea(){
if(document.entry2.name.value != ''){
return true;
}
else
if(document.entry2.year.value != ''){
return true;
}
alert('Please fill one field.');
return false;
}
</script>
</head>
which is for 1 form. I'm not sure if I did the correct thing, but in FoundStudents.jsp, where I receive the parameters of the form, I test:
if((request.getParameter("year") != null)||(request.getParameter("name") != null)){
//reading params from the SearchStudent form
................}
It works this way.

ASP.NET MVC2 InputHelper and List.Insert() strange behavior

I cannot make sense of this...
The simplified code below OUGHT to insert a new form field of the current time's second value.
Instead, even though the list manipulation happens correctly (as verifiable within the controller and in the debug output), the View does render an additional element, but seems to be just a copy of the final field's value (prior to submit). This can be verified by changing a field prior to submit - the values stick and the new element is a duplicate of the submitted final value.
The part that really cooks my noodle is that if I trivially change the operation from an Insert() to an Add(), the Add() works as expected!!
Using this example Model:
public class MyViewData
{
List<string> stringData = new List<string>();
public List<string> StringData { get { return stringData; } }
}
And this Controller:
public class TestController : Controller
{
public ActionResult Index()
{
return View(new MyViewData());
}
[HttpPost]
public ActionResult Index(MyViewData data)
{
data.StringData.Insert(0, DateTime.Now.Second.ToString());
return View(data);
}
}
And this View:
<%# Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<Forms.Controllers.MyViewData>" %>
<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
Test
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<%
System.Diagnostics.Debug.WriteLine("---");
for (var i = 0; i < Model.StringData.Count; i++)
System.Diagnostics.Debug.WriteLine("{0}", Model.StringData[i]);
%>
<% using (Html.BeginForm()) { %>
<% for (var i = 0; i < Model.StringData.Count; i++) { %>
<%: Html.TextBoxFor(model => model.StringData[i])%></br>
<% } %>
<div><input type="submit" value="Do it" /></div>
<% } %>
</asp:Content>
This is the normal behavior of standard HTML helpers and is by design. When rendering the input field they will first look at the request POSTed values and only after in the ViewData and view model. This basically means that you cannot change POSted values in your controller action.
So if you have a form with an input field:
<%= Html.TextBoxFox(x => x.Id) %>
which is posted to the following action
[HttpPost]
public ActionResult Index(MyModel model)
{
model.Id = "some new value";
return View(model);
}
when rendering the view back the html helper will use the posted value. You could either write a custom html helper that does the job for you or handle it manually (absolutely not recommended but for the record):
<input type="text" name="StringData[<%= i %>]" value="<%= Model.StringData[i] %>" />