TECHNOLOGIES
FORUMS
JOBS
BOOKS
EVENTS
INTERVIEWS
Live
MORE
LEARN
Training
CAREER
MEMBERS
VIDEOS
NEWS
BLOGS
Sign Up
Login
No unread comment.
View All Comments
No unread message.
View All Messages
No unread notification.
View All Notifications
Answers
Post
An Article
A Blog
A News
A Video
An EBook
An Interview Question
Ask Question
Forums
Monthly Leaders
Forum guidelines
Sai
NA
203
30.2k
Saving Image into database using angularjs
Aug 16 2017 7:11 AM
hi all,
i hv a piece of code , please go thru the below code and help me how to save image into database.
Backend:
=====
create table Employee(empid int primary key,name varchar(max),age int,gender varchar(max),designation varchar(max),mobile int,image varbinary(max))
Csharp code:
========
Emp.cs:
=====
public class Emp
{
public int ID { get; set; }
public string Name { get; set; }
public int Age { get; set; }
public DateTime DOB { get; set; }
public string Gender { get; set; }
public byte[] image { get; set; }
public string Designation { get; set; }
public string Mobile { get; set; }
}
========
DAL logic:
----------
public void SaveEmp(Emp emp)
{
string cs = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
SqlConnection con = new SqlConnection(cs);
con.Open();
string save = "insert into Employee values(@empid, @name, @age,@designation, @mobile,@gender,@dob)";
SqlCommand cmd = new SqlCommand(save, con);
cmd.Parameters.AddWithValue("@empid", emp.ID);
cmd.Parameters.AddWithValue("@name", emp.Name);
cmd.Parameters.AddWithValue("@age", emp.Age);
cmd.Parameters.AddWithValue("@designation", emp.Designation);
cmd.Parameters.AddWithValue("@mobile", emp.Mobile);
cmd.Parameters.AddWithValue("@gender", emp.Gender);
cmd.Parameters.AddWithValue("@dob", emp.DOB);
cmd.Parameters.AddWithValue("@dob", emp.Image);
cmd.ExecuteNonQuery();
con.Close();
}
public void UpdateEmp(Emp emp)
{
string cs = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
SqlConnection con = new SqlConnection(cs);
con.Open();
sstring update = "update Employee set name=@name, age=@age,designation=@designation, mobile=@mobile,gender=@gender,dob=@dob ,image=@image where empid=@empid";
SqlCommand cmd = new SqlCommand(save, con);
cmd.Parameters.AddWithValue("@empid", emp.ID);
cmd.Parameters.AddWithValue("@name", emp.Name);
cmd.Parameters.AddWithValue("@age", emp.Age);
cmd.Parameters.AddWithValue("@designation", emp.Designation);
cmd.Parameters.AddWithValue("@mobile", emp.Mobile);
cmd.Parameters.AddWithValue("@gender", emp.Gender);
cmd.Parameters.AddWithValue("@dob", emp.DOB);
cmd.Parameters.AddWithValue("@dob", emp.Image);
cmd.ExecuteNonQuery();
con.Close();
}
public void DeleteEmp(Emp emp)
{
string cs = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
SqlConnection con = new SqlConnection(cs);
con.Open();
string delete = "delete from Employee where empid=@empid";
SqlCommand cmd = new SqlCommand(delete, con);
cmd.Parameters.AddWithValue("@empid", emp.ID);
cmd.ExecuteNonQuery();
con.Close();
}
Home Controller.cs:
=================
Except image i wrote remaining code,Can anybody write the logic for image in HomeController and Index.cshtml page.
================================
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using AngularUiGrid.Models;
using System.Globalization;
namespace AngularUiGrid.Controllers
{
public class HomeController : Controller
{
// GET: Home
public ActionResult Index()
{
return View();
}
public JsonResult GetAllEmployee()
{
DALEmp empdal = new DALEmp();
List<Emp> employee = empdal.ListAll().ToList();
return Json(employee, JsonRequestBehavior.AllowGet);
}
[HttpPost]
public ActionResult Create(Emp employee, int pday, int pmonth, int pyear)
{
try
{
if (ModelState.ContainsKey("dob"))
{
if (ModelState["dob"].Errors.Count > 0)
{
ModelState["dob"].Errors.Clear();
}
}
employee.DOB = new DateTime(pyear, pmonth, pday);
if (ModelState.IsValid)
{
DALEmp empdal = new DALEmp();
empdal.SaveEmp(employee);
return RedirectToAction("Index");
}
else
{
ModelState.AddModelError("", "Data Not Saved");
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
return View();
}
[HttpPost]
public ActionResult Edit(Emp emp, int pday, int pmonth, int pyear)
{
#region Update
try
{
if (ModelState.ContainsKey("dob"))
{
if (ModelState["dob"].Errors.Count > 0)
{
ModelState["dob"].Errors.Clear();
}
}
emp.DOB = new DateTime(pyear, pmonth, pday);
if (ModelState.IsValid)
{
DALEmp empdal = new DALEmp();
empdal.Update(emp);
return RedirectToAction("Index");
}
else
{
ModelState.AddModelError("", "Record is not Updated");
return View();
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
return View();
#endregion
}
[HttpPost]
public ActionResult Delete(Emp emp)
{
#region Delete
try
{
if (ModelState.IsValid)
{
DALEmp empdal = new DALEmp();
empdal.DeleteEmp(emp);
return RedirectToAction("Index");
}
else
{
ModelState.AddModelError("", "Record is not Deleted");
return View();
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
return View();
#endregion
}
public ActionResult Details()
{
return View();
}
}
}
Index.cshtml code:
===========
<!DOCTYPE html>
<html>
<head>
<title>
Angularjs UI-Grid
</title>
<link href="~/Content/bootstrap.css" rel="stylesheet" />
<link href="~/Content/bootstrap-datepicker3.css" rel="stylesheet" />
<link href="~/Content/Common.css" rel="stylesheet" />
<link href="~/Content/themes/base/jquery-ui.css" rel="stylesheet" />
<link href="~/Content/ui-grid.css" rel="stylesheet" />
<script src="~/Scripts/jquery-1.12.4.min.js"></script>
<script src="~/Scripts/jquery-ui-1.12.1.js"></script>
<script src="~/Scripts/bootstrap-datepicker.js"></script>
<script src="~/Scripts/angular.min.js"></script>
<script src="~/Scripts/ui-grid.js"></script>
<script type="text/javascript">
var app = angular.module("uigridApp", ["ui.grid",'ui.grid.selection', "ui.grid.pagination"]); // module as a container for the different parts of our app – controllers, services, filters, directives, etc.
app.controller("uigridCtrl", function ($scope, $http) {
$("#DOB").datepicker({
format: 'dd/mm/yyyy',
autoclose: true,
todayHighlight: true
});
//For Age textbox
$scope.onlyNumbers = function (event) {
var keys = {
'backspace': 8,'del':46,'0': 48, '1': 49, '2': 50, '3': 51, '4': 52, '5': 53, '6': 54, '7': 55, '8': 56, '9': 57
};
for (var index in keys) {
if (!keys.hasOwnProperty(index)) continue;
if (event.charCode == keys[index] || event.keyCode == keys[index]) {
return; //default event
}
}
event.preventDefault(); //if we remove this spinner allows characters
};
// To retreive list of data.
$scope.GetAllData = function () {
$http({
method: "get",
url: "/Home/GetAllEmployee"
}).then(function (response) {
debugger;
$scope.employees = [];
for (i = 0; i < response.data.length; i++) {
var date = new Date(parseInt(response.data[i].DOB.substr(6)));
response.data[i].DOB = getFormattedDate(date);
$scope.employees.push(response.data[i])
}
}, function () {
alert("Error Occur");
})
};
$scope.gridOptions = {
data: 'employees',
paginationPageSizes: [5, 10, 20],
paginationPageSize: 5,
enableHorizontalScrollbar: 0, //hide horizontal scrollbar
enableVerticalScrollbar: 0, //hide vertical scrollbar
enableSorting: true,
enableFiltering: true,
enableRowHeaderSelection: false,
multiSelect: false,
rowHeight: 50,
headerRowHeight: 30,
columnDefs: [
{ field: 'ID', displayName: 'ID', width: 110, visible: true },
{ field: 'Name', displayName: 'Name', width: 110 },
{ field: 'Age', displayName: 'Age', width: 110 },
{ field: 'DOB', displayName: 'DOB', width: 110 },
{ field: 'Gender', displayName: 'Gender', width: 110 },
{ field: 'Designation', displayName: 'Designation', width: 110 },
{ field: 'Mobile', displayName: 'Mobile', width: 110 }, //According to this appScope, the grid has its own scope, so you need to use grid.appScope to access your application scope.
{ field: 'Edit', displayName: '', width: 110.67, cellTemplate: '<button ng-style="width:65%;" ng-click="grid.appScope.GridOnRowSelect(row.entity)" class="btn btn-warning">Edit</button>', enableSorting: false, enableFiltering: false },
{ field: 'Delete', displayName: '', width: 110.67, cellTemplate: '<button ng-style="width:65%;" ng-click="grid.appScope.Delete(row.entity)"class="btn btn-danger">Delete</button>', enableSorting: false, enableFiltering: false },
],
};
$scope.ValidationControls = function () {
// Validating the input for controls.
if ($scope.id == "") {
$scope.errormsg = "@AngularUiGrid.Common.CommonDefinitions.PleaseEnterId";
return false;
}
if ($scope.name == "") {
$scope.errormsg = "@AngularUiGrid.Common.CommonDefinitions.PleaseEnterName";
return false;
}
if ($scope.age=="" || $scope.age==null) {
$scope.errormsg = "@AngularUiGrid.Common.CommonDefinitions.PleaseEnterAge";
return false;
}
if ($scope.dob == "" || $scope.dob == null) {
$scope.errormsg = "@AngularUiGrid.Common.CommonDefinitions.EnterDate";
return false;
}
var regexDate = /^(((((0[1-9])|(1\d)|(2[0-8]))\/((0[1-9])|(1[0-2])))|((31\/((0[13578])|(1[02])))|((29|30)\/((0[1,3-9])|(1[0-2])))))\/((20[0-9][0-9])|(19[0-9][0-9])))|((29\/02\/(19|20)(([02468][048])|([13579][26]))))$/;
if (!regexDate.test($("#DOB").val())) {
$scope.errormsg ="@AngularUiGrid.Common.CommonDefinitions.EnterValidDate";
return false;
}
if ($scope.gender == "") {
$scope.errormsg = "@AngularUiGrid.Common.CommonDefinitions.PleaseEnterGender";
return false;
}
if ($scope.designation == "") {
$scope.errormsg = "@AngularUiGrid.Common.CommonDefinitions.PleaseEnterDesignation";
return false;
}
if ($scope.mobile == "") {
$scope.errormsg = "@AngularUiGrid.Common.CommonDefinitions.PleaseEnterMobile";
return false;
}
return true;
};
//the below Save function works for both insert and update data
$scope.Save = function () {
var dt = $scope.dob.split('/');
if ($scope.addEmployeeTapped) // here $scope.addEmployeeTapped is true then if block will be executed..
{
//Insert logic
$scope.ValidationControls();// if we don't give input of anyone the controls and click on Save button then ValidationControls() will work
$scope.Employe = {};
$scope.Employe.ID = $scope.id;
$scope.Employe.Name = $scope.name;
$scope.Employe.Age = $scope.age;
//DateTime oDate = Convert.ToDateTime($scope.dob);
// $scope.Employe.stringDOB = $scope.dob;
$scope.Employe.DOB = $scope.dob;
$scope.Employe.pday = dt[0];
$scope.Employe.pmonth = dt[1];
$scope.Employe.pyear = dt[2];
$scope.Employe.Gender = $scope.gender;
$scope.Employe.Designation = $scope.designation;
$scope.Employe.Mobile = $scope.mobile;
$http({
method: "post",
url: "/Home/Create",
datatype: "json",
data: JSON.stringify($scope.Employe),
}).then(function (data) {
alert("Record Added Successfully");
location.reload();
}, function (data) {
if (data == false) {
alert("Error Occur Data Not Saved");
}
})
}
else // here $scope.addEmployeeTapped is false then else block will be executed..
{
//Update Logic
$scope.ValidationControls(); // if we don't give input of anyone the controls and click on Save button then ValidationControls() will work
$scope.Employe = {};
$scope.Employe.ID = $scope.id; //$scope.id; is ng-model directive
$scope.Employe.Name = $scope.name;
$scope.Employe.Age = $scope.age;
$scope.Employe.DOB = $scope.dob;
$scope.Employe.pday = dt[0];
$scope.Employe.pmonth = dt[1];
$scope.Employe.pyear = dt[2];
$scope.Employe.Gender = $scope.gender;
$scope.Employe.Designation = $scope.designation;
$scope.Employe.Mobile = $scope.mobile;
$http({
method: "post",
url: "/Home/Edit",
datatype: "json",
data: JSON.stringify($scope.Employe),
}).then(function (data) {
alert("Record Updated Successfully");
location.reload();
}, function (data) {
if (data == false) {
alert("Error Occur Data Not Saved");
}
})
}
};//end of the Save()
function getFormattedDate(date) {
var year = date.getFullYear();
var month = (1 + date.getMonth()).toString();
month = month.length > 1 ? month : '0' + month;
var day = date.getDate().toString();
day = day.length > 1 ? day : '0' + day;
return day + '/' + month + '/' + year;
}
// For Delete[ date]
function getFormattedDate1(date) {
var year = date.getFullYear();
var month = (1 + date.getMonth()).toString();
month = month.length > 1 ? month : '0' + month;
var day = date.getDate().toString();
day = day.length > 1 ? day : '0' + day;
return year + '/' + month + '/' + day;
}
// GridOnRowSelect() For Click on Edit button
$scope.GridOnRowSelect = function (Employee) {
$scope.addEmployeeTapped = false;
$scope.id = Employee.ID; //here we are binding / holding data[Employee.ID] into ng-model directive value [ $scope.id]
$scope.name= Employee.Name;
$scope.age = Employee.Age;
// var date = new Date(parseInt(Employee.DOB.substr(6)));
$scope.dob = Employee.DOB;
$scope.gender = Employee.Gender;
$scope.designation = Employee.Designation;
$scope.mobile = Employee.Mobile;
$scope.errormsg = "";
$("#myModal").modal({
backdrop: 'static', // if we click on outside the popup then it will not close, until we click on cancel button
keyboard: false,
});
};
$scope.Delete = function (employee) {
debugger;
var date = Date(employee.DOB).toString()
var myDate = new Date(date);
employee.DOB = getFormattedDate1(myDate);
var state = confirm('Are you sure to delete?');
if (state == true) {
$http({
method: "post",
url: '/Home/Delete',
datatype: "json",
data: JSON.stringify(employee)
}).then(function (response) {
alert("Record Deleted Successfully");
location.reload();
}, function () {
alert("Error Occur in deletion");
})
}
};
$scope.openModal = function () {
$scope.id = "";
$scope.name = "";
$scope.age = "";
$scope.dob = "";
$scope.gender = "";
$scope.designation = "";
$scope.mobile = "";
$scope.errormsg = "";
$scope.addEmployeeTapped = true;
$("#myModal").modal({
backdrop: 'static', // if we click on outside the popup then it will not close until click on cancel button
keyboard: false,
});
};
});
</script>
</head>
<body ng-app="uigridApp" ng-controller="uigridCtrl">
<h2>AngularJS UI Grid</h2>
<div style="text-align:right">
<button type="button" class="btn btn-primary" data-toggle="modal" ng-click="openModal()">Add New Employee</button>
</div>
<div ui-grid="gridOptions" ui-grid-pagination ui-grid-selection class="myGrid" ng-init="GetAllData()">
@*ui-grid-pagination provides paging style for grid. if we remove it then paging cannot displayed*@
</div> @*ui-grid-selection provides style for selected row.if we remove it then row selection cannot be done*@
<div id="myModal" class="modal fade" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">x</button>
<div class="modal-title">Save Details</div>
</div>
<div class="modal-body">
<table style="width:100%">
<tr>
<td colspan="4">
<label class="lblErrorMsg" ng-bind="errormsg"> </label>
</td>
</tr>
<tr>
<td style="width:15%">
<label class="lblFont" for="ID">Id <span class="lblMandatory">*</span></label>
</td>
<td>
@Html.TextBox("Id", string.Empty, new { @class = "ControlWidth", ng_model = "id" })
</td>
</tr>
<tr>
<td style="width:15%">
<label class="lblFont" for="Name">Name <span class="lblMandatory">*</span></label>
</td>
<td>
@Html.TextBox("Name", string.Empty, new { @class = "ControlWidth", ng_model = "name" })
</td>
</tr>
<tr>
<td style="width:15%">
<label class="lblFont" for="Age">Age <span class="lblMandatory">*</span></label>
</td>
<td>
@Html.TextBox("Age", string.Empty, new { @class = "ControlWidth", ng_model = "age", ng_keypress = "onlyNumbers($event)", type = "number", min = "1", max = "100" })
</td>
</tr>
<tr>
<td style="width:15%">
<label class="lblFont" for="Date">DOB <span class="lblMandatory">*</span></label>
</td>
<td>
@Html.TextBox("DOB", string.Empty, new { @class = "ControlWidth", ng_model = "dob" })
</td>
</tr>
<tr>
<td style="width:15%">
<label class="lblFont" for="Gender">Gender <span class="lblMandatory">*</span></label>
</td>
<td>
@Html.DropDownList("Gender", new List<SelectListItem>() { new SelectListItem { Text="Male",Value="Male"},
new SelectListItem {Text="Female",Value="Female"}}, "--Select List--", new { @class = "ControlWidth", ng_model = "gender" })
</td>
</tr>
<tr>
<td style="width:17%">
<label class="lblFont" for="Designation"> Designation <span class="lblMandatory">*</span></label>
</td>
<td>
@Html.TextBox("Designation", string.Empty, new { @class = "ControlWidth", ng_model = "designation" })
</td>
</tr>
<tr>
<td style="width:15%">
<label class="lblFont" for="Mobile">Mobile <span class="lblMandatory">*</span></label>
</td>
<td>
@Html.TextBox("Mobile", string.Empty, new { @class = "ControlWidth", ng_model = "mobile" })
</td>
</tr>
</table>
</div>
<div class="modal-footer">
<input type="button" class="btn btn-success" ng-click="Save()" value="Save" />
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
</div>
</div>
</div>
</div>
</body>
</html>
Regards,
Reply
Answers (
2
)
hide control without consuming space in xcode using swift?
After max characters per line in textarea, text in next line