var JobSpeciality = Request.Form["productId"];
var Wishes = Request.Form["Wishes"];
//var OptionalInfo = Request.Form["OptionalInfo"];
if (IsPost && Validation.IsValid()) {
// Define the insert query. The values to assign to the
// columns in the Product table are defined as parameters
// with the VALUES keyword.
//Pe noi ne intereseaza: IdEducation, Diplomes, Experience, ExperienceDetails, JobType, JobSpeciality, Wishes
if(ModelState.IsValid) {
var insertQuery = "INSERT INTO JobApplications (IdUser, IdEducation, EducationDetails, Diplomes, Experience, ExperienceDetails, JobType, JobSpeciality, Wishes, AtachedCV) " +
"VALUES (@0, @1, @2, @3, @4, @5, @6, @7, @8, @9)";
db.Execute(insertQuery, TheUserID, Education, EducationDetails, Diplomes, Experience, ExperienceDetails, JobType, JobSpeciality, Wishes, AtachedCV);
@: Application data was inserted;
// Display the page that lists products.
Response.Redirect("~/Succes");
}
}
but I don't know how to deal with the content of the binary file. Also I have no ideea if I succed to upload the content to the table, how to make it then available to the relevant users in a table or grid rendering page.
Another problem that bother me is about two cascading dropndown lists (the two lists are intended to be filled with data from corespondant tables).
The second dropdown loose somehow the value (it keeps only the text atributte) . If I execute the insert into table, the value for the first DDL is inserted, but the value for the second it seems to me that it does not exist.
thank you ind advance.
L.E.
I just wonder if an approach like this, can work for the cascading DDL:
<label for="Domain">Domain: </label>
<br/>
<select name="Domain" tabindex="1" id="Domain">
<option value="" selected="selected">Please Choose</option>
var selectJobTypes = "SELECT IdJobType, JobType FROM JobTypes ORDER BY IdJobType";
var dataJT = db.Query(selectJobTypes);
@foreach (var row in dataJT)
{
<option value=@row.IdJobType>@row.JobType</option>
}
</select>
<br/>
<label for="Speciality">Speciality: </label>
<br/>
<select name="Speciality" tabindex="1" id="Speciality">
<option value="" selected="selected">Please Choose</option>
var selectJobSpeciality = "SELECT IdJobSpeciality, IdJobType, Speciality FROM JobSpeciality WHERE IdJobType ="+ @row.IdJobType +" ORDER BY IdJobSpeciality";
var dataJS = db.Query(selectJobSpeciality);
@foreach (var row in dataJS)
{
<option value=@row.IdJobSpeciality>@row.Speciality</option>
}
</select>
<br/>
L.L.E
The upload issue is solved:
var UploadedPicture = Request.Files[0];
byte[] Picture;
if (Path.GetFileName(UploadedPicture.FileName) != String.Empty)
{
var ContentType = UploadedPicture.ContentType;
var ContentLength = UploadedPicture.ContentLength;
var InputStream = UploadedPicture.InputStream;
Picture = new byte[ContentLength];
InputStream.Read(Picture, 0, ContentLength);
}
else
{
Picture = new byte[0];
}
was in a wrong place, before the if(IsPost...
I moved inside and it's working now. I just wonder if the approach is a corect one?! Maybe is more useful to upload the file(s) to a folder and to save in the table the url? Finally I need that an user that see the page with the table content to be able
to see/download the attached *.pdf or *.doc file.
So in this moment the only issue that remins critical for me is the unability to use the cascadind DDL properly.
I’m glad to hear that you have solved your first issue by yourself, and it is very appreciated to share your solution to us. It will be helpful for others.
About your second issue “Maybe is more useful to upload the file(s) to a folder and to save in the table the url?”
I can tell you that this method is not security, but if you save the files to DB, it will use a lot of database resources. So choose which method depends on your situation.
About your third issue I give you an example.
Here is simple code about how to show byte info from DB as picture.
try
{
SqlConnection sqlConnection = new SqlConnection(@"Data Source=.\xx;Initial Catalog=ImageTest;Integrated Security=True");
sqlConnection.Open();
string comText = "Select ImageData from ImageTable";
SqlCommand sqlCommand = new SqlCommand(comText, sqlConnection);
SqlDataReader dr = sqlCommand.ExecuteReader();
dr.Read();
MemoryStream ms = new MemoryStream((byte[])dr[0] );
thank for all replays to date (from all contributors).
My cascaded DDL issue is in a Webmatrix project, and I am very new to razor syntax. I am more familiar with clasic web forms approach (with code behind and so on)
Here is an example using jQuery. In this example I get a list of counties and their ids for the dropdown from the database. Districts (DD) is the cascading dropdown.
@{
var db = Database.Open("myDatabase");
var data = db.Query("SELECT countyID, countyName FROM counties");
var items = data.Select(i => new SelectListItem
{
Value = i.countyID.ToString(),
Text = i.countyName
});
}
@{
// Validate Form Input
if (IsPost)
{
@:CountyID: @Request.Form["countyID"]<br />
@:DistrictID: @Request.Form["DD"]<br />
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title></title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1/jquery-ui.min.js"></script>
</head>
<body>
<form method="post" action="" name="frmDist">
@Html.DropDownList("countyID", "Please Select One", items)
<select id="DD" name="DD">
<option>Select County First</option>
</select>
<p>
<input id="submit" title="Submit" name="submit"
value="Submit" tabindex="900"
type="submit" />
</p>
</form>
<script type="text/javascript">
$(function () {
$("#countyID").change(function () {
var selectedCounty = $(this).val();
$.getJSON('Test2.cshtml', { countyID: selectedCounty }, function (districts) {
var districtSelect = $('#DD');
districtSelect.empty();
$.each(districts, function (index, district) {
districtSelect.append(
$('<option/>')
.attr('value', district.districtID)
.text(district.districtName)
);
});
});
});
});
</script>
</body>
</html>
Then a second web page, in this case named Test2.cshtml, is for retrieving the District Name and ID for the cascading dropdown.
@{
var db = Database.Open("myDatabase");
var source = db.Query("SELECT districtID, districtName FROM districts WHERE countyID = @0", Request["countyID"]);
Json.Write(source, Response.Output);
}
I adapted the code to my needs, and if it is inserted in a regular .cshtml page it works well. But my web-app is implemented using _Sitelayout.cshtml and page.cshtml pairs.
In this context, I moved the <script></script> from page to just before the </body> of _Sitelayout.cshtml, the refs to jquery.min and jquery-ui.min.js in the <head> section of _Sitelayout.cshtml (btw I also have refs to jquery.js) and all the rest is in
the code of the page.
@{
Layout = "~/_SiteLayout.cshtml";
Page.Title = "Register";
//The DB stuff
var db = Database.Open("SQLServerConnectionString");
var TheUserName = "";
if (WebSecurity.IsAuthenticated) {TheUserName = @WebSecurity.CurrentUserName;}
var SelectUserID = "Select UserID FROM UserProfile WHERE Email ='" + TheUserName +"'";
var dataUserId = db.Query(SelectUserID);
var TheUserID = 0;
foreach (var row in dataUserId)
{TheUserID=@row.UserID;}
//Here comes the data for the first DDL
var data = db.Query("SELECT IdJobType, JobType FROM JobTypes ORDER BY IdJobType");
var items = data.Select(i => new SelectListItem
{
Value = i.IdJobType.ToString(), //was countyID
Text = i.JobType //was countyName
});
var Education = Request.Form["Education"];
var EducationDetails = Request.Form["EducationDetails"];
var Diplomes = Request.Form["Diplomes"];
var Experience = Request.Form["Experience"];
var ExperienceDetails = Request.Form["ExperienceDetails"];
var Wishes = Request.Form["Wishes"];
// Initialize general page variables
var email = "";
var password = "";
var confirmPassword = "";
var FirstName = "";
var LastName = "";
var HomePhone = "";
var WorkPhone = "";
var CellPhone = "";
// Setup validation
// If this is a POST request, validate and process data
if (IsPost) {
AntiForgery.Validate();
email = Request.Form["email"];
password = Request.Form["password"];
confirmPassword = Request.Form["confirmPassword"];
//Display the selection of the two DDL for debug purpose
@:You choose Domain: @Request.Form["SelectJType"]<br />
@:You choose Speciality: @Request.Form["SelectSType"]<br />
// If all information is valid, create a new account
if (Validation.IsValid()) {
// Insert a new user into the database
//var db = Database.Open("SQLServerConnectionString");
// Check if user already exists
var user = db.QuerySingle("SELECT Email FROM UserProfile WHERE LOWER(Email) = LOWER(@0)", email);
if (user == null) {
// Insert email into the profile table
db.Execute("INSERT INTO UserProfile (Email) VALUES (@0)", email);
//Dual insert implementation
//db.Execute(insertQuery, Category);
//var id = (int)db.GetLastInsertId(); //id is the new CategoryId
//db.Execute(secondInsertQuery, param1, id);
// Create and associate a new entry in the membership database.
// If successful, continue processing the request
try {
bool requireEmailConfirmation = !WebMail.SmtpServer.IsEmpty();
var token = WebSecurity.CreateAccount(email, password, requireEmailConfirmation);
if (requireEmailConfirmation) {
var hostUrl = Request.Url.GetComponents(UriComponents.SchemeAndServer, UriFormat.Unescaped);
var confirmationUrl = hostUrl + VirtualPathUtility.ToAbsolute("~/Account/Confirm?confirmationCode=" + HttpUtility.UrlEncode(token));
WebMail.Send(
to: email,
subject: "Please confirm your account",
body: "Your confirmation code is: " + token + ". Visit <a href=\"" + confirmationUrl + "\">" + confirmationUrl + "</a> to activate your account."
);
}
if (requireEmailConfirmation) {
// Thank the user for registering and let them know an email is on its way
Response.Redirect("~/Account/Thanks");
} else {
// Navigate back to the homepage and exit
WebSecurity.Login(email, password);
Response.Redirect("~/");
}
} catch (System.Web.Security.MembershipCreateUserException e) {
ModelState.AddFormError(e.Message);
}
} else {
// User already exists
ModelState.AddFormError("Email address is already in use.");
}
}
}
}
@section featured {
<section class="featured">
<div class="content-wrapper">
<hgroup class="title">
<h2>@Page.Title</h2>
<h3>Registering with the site gives you access to all relevant resources.</h3>
</hgroup>
</div>
</section>
}
<div class="wrapper row3">
<div id="container" class="clear">
<form method="post">
@AntiForgery.GetHtml()
@* If at least one validation error exists, notify the user *@
@Html.ValidationSummary("Account creation was unsuccessful. Please correct the errors and try again.", excludeFieldErrors: true, htmlAttributes: null)
<div id="UserZone" class="registerzone">
<fieldset>
<legend>Registration Form, User Information</legend>
</fieldset>
</div>
<div id="CVZone" class="registerzone">
<fieldset>
<legend>Registration Form, Detailed CV Information</legend>
<strong>CV Information</strong>
<ol>
<li>
<label for="Grades">Your Grade(s):</label>
<br/>
<textarea name="Grades" tabindex="5" cols="40" rows=4></textarea>
</li>
<li>
<label for="SelectJType">Domain (lookup): </label>
<br/>
<!-- first DDL -->
@Html.DropDownList("SelectJType", "-- Please Select One --", items)
</li>
<li>
<label for="SelectSType">Speciality (lookup)</label>
<br/>
<!-- second DDL -->
<select id="SelectSType" name="SelectSType">
<option>-- Please Select Job Type First --</option>
</select>
</li>
<li>
<label for="Wishes">Wishes: </label>
<br/>
<textarea name="Wishes" tabindex="7" cols=40 rows=3></textarea>
</li>
</ol>
</fieldset>
</div>
<div id="SubmitZone" class="registerzone">
<fieldset>
<legend>Submit Zone</legend>
<input type="submit" value="Register" />
</fieldset>
</div>
</form>
</div>
</div>
<!--Script for cascading DDL -->
<script type="text/javascript">
$(function () {
//specialitySelect.attr('disabled', true);
var specialitySelect = $('#SelectSType');
specialitySelect.attr('disabled', true);
$("#SelectJType").change(function () {
var selectedJob = $(this).val();
$.getJSON('HelperPage.cshtml', { IdJobType: selectedJob }, function (JobSpeciality) {
//var specialitySelect = $('#SelectSType');
specialitySelect.attr('disabled', false);
specialitySelect.empty();
specialitySelect.append(
$('<option/>')
.attr('value', '')
.text('-- Please Select Speciality --'));
$.each(JobSpeciality, function (index, speciality) {
specialitySelect.append(
$('<option/>')
.attr('value', speciality.IdJobSpeciality)
.text(speciality.Speciality)
);
});
});
});
});
</script>
and the HelperPage.cshtml as follows:
@{
var db = Database.Open("SQLServerConnectionString");
//Here comes data for the second DDL
var source = db.Query("SELECT IdJobSpeciality, Speciality FROM JobSpeciality WHERE IdJobType = @0", Request["IdJobType"]);
Json.Write(source, Response.Output);
}
So where I am doing something wrong, because in this second scenario, it does not work?!
in this particular case, may page is not in the root, but in an "account" folder. On the other hand HelperPage.cshtml is in root. By out of habit, in the jquery script section, I spelled with RAZOR syntax:
$.getJSON('~/HelperPage.cshtml'
instead of:
$.getJSON('../HelperPage.cshtml'
Now all works
The only thing that bother me in this moment is that if I reload the page by any reason before I submit the form, the first DDL is allready preselected with the last choice I made, and for this I have first to select another item, then revert to what I want,
for being able to activate and select the second DDL.
So I am not sure why is not initialized when I reload the page.
Any way thanx for all responses so far, from all contributors.
I think that I have bad-luck: The cascading DDL are again don't work. In the last week a made some changes in order to add a kind of support for jQuery date-picker, multi language pages, and support for jHTMLArea . This consists in some changes (that I
really don't track at the moment) of jQuery's references. As I found that is messy, I changed in various combinations of versions. First effect is that if I change jquery-1.8.2.js to a newer version, JQuery date-picker cease to work.
In any combination I can't succeed to make also the cascading DDL to work again. I take a look at the Response and at least JSON is OK:
[{"IdJobSpeciality":117,"Speciality":"Aide de pharmacie"},{"IdJobSpeciality":118,"Speciality":"Pharmacien"}]<!DOCTYPE html>
[{"IdJobSpeciality":117,"Speciality":"Aide de pharmacie"},{"IdJobSpeciality":118,"Speciality":"Pharmacien"}]
I found that if I comment the line stating: Layout = "~/_SiteLayout.cshtml"; from page _StartPage.cshtml, al scripts execute properly. If I uncomment it, at least the script related to DDL goes wrong.
The only one inappropriate behavior is in this moment related to the change language dropdownlist: as figured in code, the change trigger the form post, but due to _SiteLayout.cshtml + Page.cshtml approach, in many pages I come to have more than 2 or 3 forms.
And all the forms are submitted when I made a selection to the language. (Another thing that bother me is that the language is changed on a per page basis: if I choose FR on home page, it change well, but if than I navigate e.g. to Contact, it reverts to en-GB).
Member
15 Points
115 Posts
Upload a binary file (image or pdf) and other questions
Jul 18, 2013 07:26 AM|net4u|LINK
Hello,
I have a table that contain some fields, AtachedCV and ProfilePhoto , as VarBinaryMax and I wonder how do I upload the content from the Input Form.
I have the control in the form as follows:
and this region for the Form processing;
but I don't know how to deal with the content of the binary file. Also I have no ideea if I succed to upload the content to the table, how to make it then available to the relevant users in a table or grid rendering page.
Another problem that bother me is about two cascading dropndown lists (the two lists are intended to be filled with data from corespondant tables).
I used the proof of concept from: [url]http://www.mikesdotnetting.com/Article/196/WebMatrix-jQuery-Cascading-Dropdown-Lists[/url] and the second list is well filtered, but it have only text, not also value so when I execute the insert query the field remains NULL.
Any help will be apreciated.
Laurentiu
Member
12 Points
51 Posts
Re: Upload a binary file (image or pdf) and other questions
Jul 18, 2013 08:33 AM|Marv99|LINK
I have just done this, but unfortunately I am not at my normal computer to post code. However I was using the webimage helper and this same question has been answered here using webimage: http://forums.asp.net/t/1834113.aspx/1?How+to+Attach+a+File+or+Image
check that out and if you are still having problems I can post some of my code later and explain better.
All-Star
194864 Points
28100 Posts
Moderator
Re: Upload a binary file (image or pdf) and other questions
Jul 18, 2013 08:35 AM|Mikesdotnetting|LINK
This article covers uploading and saving binary data to a database: http://www.mikesdotnetting.com/Article/148/Save-And-Retrieve-Files-From-a-Sql-Server-CE-Database-with-WebMatrix
Member
15 Points
115 Posts
Re: Upload a binary file (image or pdf) and other questions
Jul 18, 2013 09:37 AM|net4u|LINK
Hi Mike,
In what concerns the first problem, I allready found and read your article, but I am stuck at a:
Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index
error.
The upload helper is inside a form in my case.
The error rise here: var UploadedPicture = Request.Files[0];
I also take a look at the WebMatrix Photo Gallery example that is largely similar, and that example works.
But my implementation fails.
I have also a question related to your article from blog about Cascading dropdown lists: http://www.mikesdotnetting.com/Article/196/WebMatrix-jQuery-Cascading-Dropdown-Lists
The second dropdown loose somehow the value (it keeps only the text atributte) . If I execute the insert into table, the value for the first DDL is inserted, but the value for the second it seems to me that it does not exist.
thank you ind advance.
L.E.
I just wonder if an approach like this, can work for the cascading DDL:
L.L.E
The upload issue is solved:
was in a wrong place, before the if(IsPost...
I moved inside and it's working now. I just wonder if the approach is a corect one?! Maybe is more useful to upload the file(s) to a folder and to save in the table the url? Finally I need that an user that see the page with the table content to be able to see/download the attached *.pdf or *.doc file.
So in this moment the only issue that remins critical for me is the unability to use the cascadind DDL properly.
Member
215 Points
29 Posts
Re: Upload a binary file (image or pdf) and other questions
Jul 19, 2013 05:46 AM|Javen Yao - MSFT|LINK
I’m glad to hear that you have solved your first issue by yourself, and it is very appreciated to share your solution to us. It will be helpful for others.
About your second issue “Maybe is more useful to upload the file(s) to a folder and to save in the table the url?”
I can tell you that this method is not security, but if you save the files to DB, it will use a lot of database resources. So choose which method depends on your situation.
About your third issue I give you an example.
Here is simple code about how to show byte info from DB as picture.
try
{
SqlConnection sqlConnection = new SqlConnection(@"Data Source=.\xx;Initial Catalog=ImageTest;Integrated Security=True");
sqlConnection.Open();
string comText = "Select ImageData from ImageTable";
SqlCommand sqlCommand = new SqlCommand(comText, sqlConnection);
SqlDataReader dr = sqlCommand.ExecuteReader();
dr.Read();
MemoryStream ms = new MemoryStream((byte[])dr[0] );
Image img = Image.FromStream(ms);
pictureBox1.Image = img;
sqlConnection.Close();
}
catch (SqlException ex)
{
…
}
For cascading DDL part, you can refer to this: http://www.aspdotnet-suresh.com/2011/01/introduction-here-i-will-explain-how-to.html
Feedback to us
Member
15 Points
115 Posts
Re: Upload a binary file (image or pdf) and other questions
Jul 19, 2013 06:36 AM|net4u|LINK
thank for all replays to date (from all contributors).
My cascaded DDL issue is in a Webmatrix project, and I am very new to razor syntax. I am more familiar with clasic web forms approach (with code behind and so on)
Member
690 Points
185 Posts
Re: Upload a binary file (image or pdf) and other questions
Jul 19, 2013 09:49 AM|dblaire|LINK
Here is an example using jQuery. In this example I get a list of counties and their ids for the dropdown from the database. Districts (DD) is the cascading dropdown.
Then a second web page, in this case named Test2.cshtml, is for retrieving the District Name and ID for the cascading dropdown.
Member
15 Points
115 Posts
Re: Upload a binary file (image or pdf) and other questions
Jul 25, 2013 10:35 AM|net4u|LINK
Hi,
I adapted the code to my needs, and if it is inserted in a regular .cshtml page it works well. But my web-app is implemented using _Sitelayout.cshtml and page.cshtml pairs.
In this context, I moved the <script></script> from page to just before the </body> of _Sitelayout.cshtml, the refs to jquery.min and jquery-ui.min.js in the <head> section of _Sitelayout.cshtml (btw I also have refs to jquery.js) and all the rest is in the code of the page.
In this scenario, it simply don't work.
thnx
Laurentiu
Member
690 Points
185 Posts
Re: Upload a binary file (image or pdf) and other questions
Jul 25, 2013 11:30 AM|dblaire|LINK
The refs to jquery in _Sitelayout.cshtml is fine. But <script></script> needs to be on the page.cshtml not _Sitelayout.cshtml.
Member
15 Points
115 Posts
Re: Upload a binary file (image or pdf) and other questions
Jul 25, 2013 12:06 PM|net4u|LINK
thnx for response.
unfortunatelly it still does not work in the Layout + Page implemenation.
In this implementation as Page.cshtml all is working OK:
But in reality I have (simplified version) _Sitelayout.cshtml as follows:
and let say TestPage.cshtml as follows:
and the HelperPage.cshtml as follows:
So where I am doing something wrong, because in this second scenario, it does not work?!
Member
15 Points
115 Posts
Re: Upload a binary file (image or pdf) and other questions
Jul 25, 2013 04:29 PM|net4u|LINK
I found it:
in this particular case, may page is not in the root, but in an "account" folder. On the other hand HelperPage.cshtml is in root. By out of habit, in the jquery script section, I spelled with RAZOR syntax:
instead of:
Now all works
The only thing that bother me in this moment is that if I reload the page by any reason before I submit the form, the first DDL is allready preselected with the last choice I made, and for this I have first to select another item, then revert to what I want, for being able to activate and select the second DDL.
So I am not sure why is not initialized when I reload the page.
Any way thanx for all responses so far, from all contributors.
Member
15 Points
115 Posts
Re: Upload a binary file (image or pdf) and other questions
Aug 07, 2013 07:19 AM|net4u|LINK
I think that I have bad-luck: The cascading DDL are again don't work. In the last week a made some changes in order to add a kind of support for jQuery date-picker, multi language pages, and support for jHTMLArea . This consists in some changes (that I really don't track at the moment) of jQuery's references. As I found that is messy, I changed in various combinations of versions. First effect is that if I change jquery-1.8.2.js to a newer version, JQuery date-picker cease to work.
In any combination I can't succeed to make also the cascading DDL to work again. I take a look at the Response and at least JSON is OK:
Also, in the script code:
what is before (no matter what, I moved code from after this line)
$("#SelectJType").change(function () is executed.
So here I am stuck...
Member
15 Points
115 Posts
Re: Upload a binary file (image or pdf) and other questions
Aug 07, 2013 01:21 PM|net4u|LINK
I am unstuck now: as I sayid, I implemented a kind (of) mechanism for changing language. This consists in followind:
1.) A file _PageStart.cshtml wich contains:
and then
2.) in _SiteLayout.cshtml I have:
I found that if I comment the line stating: Layout = "~/_SiteLayout.cshtml"; from page _StartPage.cshtml, al scripts execute properly. If I uncomment it, at least the script related to DDL goes wrong.
The only one inappropriate behavior is in this moment related to the change language dropdownlist: as figured in code, the change trigger the form post, but due to _SiteLayout.cshtml + Page.cshtml approach, in many pages I come to have more than 2 or 3 forms. And all the forms are submitted when I made a selection to the language. (Another thing that bother me is that the language is changed on a per page basis: if I choose FR on home page, it change well, but if than I navigate e.g. to Contact, it reverts to en-GB).
How can I avoid this?
many thanks
Laurentiu