Click Here For MCQ

Tuesday, June 30, 2020

Responsive image Box Upload with save in database path with stylesheet in Asp.net MVC

 image must name --- noImg



image must nm- browse-img
 
Model


public class tbl_user
    {
        public HttpPostedFileBase Userimagefile { get; set; }

        public string Imgpath { get; set; }
    }


View



@model CodeFirstProject.Models.tbl_user
@{
    ViewBag.Title = "imgview";
}

<h2>imgview</h2>
<link href="~/Contentstylesheet/ProfileStyleSheet.css" rel="stylesheet" />
<link href="~/Content/bootstrap.min.css" rel="stylesheet" />

<head>


</head>
@using (Html.BeginForm("imgview", "Home", FormMethod.Post, new { @class = "form-horizontal", enctype = "multipart/form-data" }))
{
        <div class="container">
    <div class="row">
        <div class="col-md-4">
            <div class="user-pro-img">

                <input type="file" class="hidden" id="Browseimg" accept="image/*" name="Userimagefile"/>
                <img src="~/Content/noImg.jpg" class="img-responsive" id="userimg" />
                <p class="image-des text-center">Allowed Image Size : 3500*2933px</p>
                <div class="upload-photo">
                    <img src="~/Content/browse-img.png" class="img-responsive" />
                </div>
                <div class="remove-photo">
                    <span class="glyphicon glyphicon-remove" >

                    </span>

                </div>
            </div>
        </div>
    </div>
</div>
<div class="row">
    <div class="col-md-2">
        <input type="submit" value="Submit" />

    </div>
</div>
}
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script>

    $('#userimg').click(function () {
        clickevent();
    });
    $('.upload-photo').click(function () {
        clickevent();
    });

    function clickevent()
    {
        $('#Browseimg').trigger('click');
    }

    $('#Browseimg').change(function () {
        var files = this.files;

        if (files && files[0]) {
            var filereader = new FileReader();
            filereader.readAsDataURL(files[0]);
            filereader.onload = function (x) {

                var imgs = new Image;
                imgs.src = x.target.result;
                imgs.onload = function () {
                    var width = this.width;
                    var height = this.height;
                    var type = files[0].type;
                    if ((width <= "3500" && height <= "2933") &&(type =="image/png" ||type =="image/jpg" || type =="image/jpeg"))
                    {
                        $('#userimg').attr('src', x.target.result);
                        $('.image-des').css("color", "black");
                    }
                    else {
                        $('.image-des').css("color", "red");

                    }
                 //   alert("width" +width +"height" +height +"type" +type )

                }
                 
                
            }
        }
    });

    $('.remove-photo').click(function () {
        $('#userimg').attr('src', "/Content/noImg.jpg");
    })
</script>



Controller



 public ActionResult imgview()
        {

            return View();
        }
        [HttpPost]
        public ActionResult imgview(tbl_user ss)
        {
            string filename = Path.GetFileNameWithoutExtension(ss.Userimagefile.FileName);
            string extension = Path.GetExtension(ss.Userimagefile.FileName);

            filename = filename + DateTime.Now.ToString("yymmssff") + extension;
            ss.Imgpath = "~/Img" + filename;
            filename = Path.Combine(Server.MapPath("~/Img"), filename);
            ss.Userimagefile.SaveAs(filename);



            db.Entry(ss).State = System.Data.Entity.EntityState.Modified;
            db.SaveChanges(); 
            return View();
        }


Stylesheet css



body {
}


.user-pro-img{
    /*border:1px solid #ededed;
    border-radius:3px;*/

}

.user-pro-img img{
    height:300px;
    cursor:pointer;
    
}
.user-pro-img:hover .upload-photo{
    transform:scaleY(1);
}
.user-pro-img .upload-photo{
    background-color: #242424;
    opacity: 0.4;
    width: 92%;
    height: 50px;
    position: absolute;
    bottom : 28px;
    left: 15px;
    cursor : pointer;
    transform:scaleY(0);
    transition:0.3s;
    transform-origin:bottom;

}

.user-pro-img .upload-photo:before{
    content: 'Change Photo';
    color : #eff;
    position: absolute;
    bottom: 10px;
    left: 110px;
    opacity:1;
    font-size:24px;
}

.user-pro-img .upload-photo img{
    height: 30px;
    width : 30px;
    color : #eff;
    position : absolute;
    top : 7px;
    left : 70px;
}

.user-pro-img .remove-photo{
    position: absolute;
    top: 0;
    right:15px;
    border: 2px solid #ddd;
    padding : 10px;
    cursor: pointer;
    transform :scale(0);
    transition:0.3s;
    transform-origin:top;
}

.user-pro-img .remove-photo .glyphicon-remove{
    color:#ededed;
}

.user-pro-img .remove-photo:hover .glyphicon-remove{
    color:#808080;

}

.user-pro-img:hover .remove-photo{
    transform :scale(1);
}



Sunday, June 28, 2020

Code first Approach to Entity Model

You should remember that you must download entity frame work from nuget pakasge manager



public class Student
    {
        [Key]
        public int StudentId { get; set; }
        public string Name { get; set; }
        public int standard { get; set; }
        public string CollegeName { get; set; }
        public string Address { get; set; }

    }



    public class StudentContext : DbContext
    {
        public DbSet<Student> Students { get; set; }
    }


web config

 <entityFramework>
    <providers>
      <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
    </providers>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
      <parameters>
        <parameter value="mssqllocaldb" />
      </parameters>
    </defaultConnectionFactory>
  </entityFramework>
  <connectionStrings>
    <add name="StudentContext" connectionString="Data Source=(LocalDB)\MSSQLLocalDB; Initial catalog=CodeFirstEFDB; Integrated Security=true;" providerName="System.Data.SqlClient" />
  </connectionStrings>
</configuration>






Friday, June 26, 2020

Update and Edit entityframework asp.net mvc

public class HomeController : Controller
    {
        StudentContext db = new StudentContext();
        // GET: Home
        public ActionResult Index()
        {
            var ad =db.Students.ToList();
            return View(ad);
        }

        public ActionResult edit(int id = 0)
        {
            var data = db.Students.Where(m => m.StudentId == id).FirstOrDefault();
            return View(data);
        }
        [HttpPost]
        public ActionResult edit(Student s)
        {
            db.Entry(s).State = EntityState.Modified;
            db.SaveChanges();
            return RedirectToAction("Index");
        }

Thursday, June 25, 2020

Insert Data with the help of DapperORM with store procedure in ASP.Net MVC C#

install dapper orm version 1.42 nuget pakage only with mvc it is must 


you can also perform entityframe work with dapperorm it is tested


public class DapperOrm
    {
        private static string connectionstring = @"Data Source=(LocalDB)\MSSQLLocalDB; Initial Catalog=mystore; Integrated Security=True;";

      public static void Executewithoutreturn(string procedureName ,DynamicParameters param =null)
        {
            using (SqlConnection sqlcon =new SqlConnection(connectionstring))
            {
                sqlcon.Open();
                sqlcon.Execute(procedureName, param, commandType: CommandType.StoredProcedure);

            }
        }
        //DapperOrm.ExecutewithreturnScaler<int>("","");
        public static T ExecutewithreturnScaler<T>(string procedureName, DynamicParameters param=null)
        {
            using (SqlConnection sqlcon = new SqlConnection(connectionstring))
            {
                sqlcon.Open();
                return (T)Convert.ChangeType(sqlcon.Execute(procedureName, param, commandType: CommandType.StoredProcedure),typeof(T));

            }
        }
        ///DapperOrm.ReturnList<Employeemodel>("","");
        public static IEnumerable<T> ReturnList<T>(string procedureName, DynamicParameters param =null)
        {
            using (SqlConnection sqlcon = new SqlConnection(connectionstring))
            {
                sqlcon.Open();
                return sqlcon.Query<T>(procedureName, param, commandType: CommandType.StoredProcedure);

            }
        }
    }
}



mypracticemodel


public class mypracticemodel
    {
        public int id { get; set; }
        public string firstname { get; set; }
        public string sirname { get; set; }
    }



controller



 public class HomeController : Controller
    {
        // GET: Home
        public ActionResult Index()
        {
            return View();
        }
        [HttpPost]

        public ActionResult Index(mypracticemodel emp)
        {
            DynamicParameters param = new DynamicParameters();
            param.Add("@id", emp.id);
            param.Add("@firstname", emp.firstname);
            param.Add("@sirname", emp.sirname);
            DapperOrm.Executewithoutreturn("sp_newinsert", param);

            return View();
        }

        public ActionResult viewlist()
        {
            return View(DapperOrm.ReturnList<Employeemodel>("sp_selectlisttable"));
        }



view 


@model DapperProj.Models.mypracticemodel

@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>


@using (Html.BeginForm()) 
{
    @Html.AntiForgeryToken()
    
    <div class="form-horizontal">
        <h4>mypracticemodel</h4>
        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        <div class="form-group">
            @Html.LabelFor(model => model.firstname, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.firstname, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.firstname, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.sirname, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.sirname, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.sirname, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Create" class="btn btn-default" />
            </div>
        </div>
    </div>
}

<div>
    @Html.ActionLink("Back to List", "Index")
</div>

<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script src="~/Scripts/jquery.validate.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>




database
store procedure


USE [mystore]
GO
/****** Object:  StoredProcedure [dbo].[sp_newinsert]    Script Date: 6/25/2020 9:44:04 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER proc [dbo].[sp_newinsert]
@id int,
@firstname nvarchar(50),
@sirname nvarchar(50)
as
insert into mypractice (firstname,sirname)
values (@firstname,@sirname)

Casecade Dropdown by Databasein Asp.Net Mvc C#

create table dbo.country
(
Cid int not null identity(1,1) primary key,
Cname varchar(100)
);

create table dbo.State 
(
Sid int not null identity(1,1) primary key,
Sname varchar(100),
Cid int
);

create table dbo.city
(
Cityid int not null identity(1,1) primary key,
Cityname varchar(100),
Sid int
);


Home Controller


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Casdropdown.Models;

namespace Casdropdown.Controllers
{
    public class HomeController : Controller
    {
        // GET: Home
        public ActionResult Index()
        {
            studentEntities db = new studentEntities();
            ViewBag.country = new SelectList(Getcountrylist(), "Cid", "Cname");
            return View();
        }

        public List<country> Getcountrylist()
        {
            studentEntities sd = new studentEntities();
            List<country> countries = sd.countries.ToList();
            return countries;
        }

        public ActionResult GetstateList(int Cid)
        {
            studentEntities db = new studentEntities();
            List<State> selectList = db.States.Where(x => x.Cid == Cid).ToList();
            ViewBag.Slist = new SelectList(selectList, "Sid", "Sname");
            return PartialView("DisplayState");
        }

        public ActionResult GetCityList(int Sid)
        {
            studentEntities db = new studentEntities();
            List<city> selectList = db.cities.Where(x => x.Sid == Sid).ToList();
            ViewBag.Citylist = new SelectList(selectList, "Cityid", "Cityname");
            return PartialView("Displaycity");
        }
    }
}


View
Index View


@model Casdropdown.Models.Cascadingclass
@{
    ViewBag.Title = "Index";
}

<h2>Cascading Dropdown list</h2>

@if (ViewBag.country!=null)
{
    @Html.DropDownListFor(m =>m.Cid, ViewBag.country as SelectList,"--Select Country Name---" ,new { @class="form-control"})
}
@Html.DropDownListFor(m => m.Sid, new SelectList(""), "--Select State Name---", new { @class = "form-control" })

@Html.DropDownListFor(m => m.Cityid, new SelectList(""), "--Select City Name---", new { @class = "form-control" })




<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script>
    $(document).ready(function () {
        $("#Cid").change(function () {
            var countryId = $(this).val();
           // debugger
            $.ajax({
                type: "post",
                url: "/Home/GetstateList?Cid=" + countryId,
                contentType: "html",
                success: function (response) {
                    console.log(response)
                 //   debugger
                    $("#Sid").empty();
                    $("#Sid").append(response);

                }
            })
        })
        $("#Sid").change(function () {
            var stateId = $(this).val();
            // debugger
            $.ajax({
                type: "post",
                url: "/Home/GetCityList?Sid=" + stateId,
                contentType: "html",
                success: function (response) {
                    console.log(response)
                    //   debugger
                    $("#Cityid").empty();
                    $("#Cityid").append(response);

                }
            })
        })
    })
</script>



Shared Partial View
DisplayState Partial.cshtml





@model Casdropdown.Models.State

<option value="">--Select State--</option>

@if (ViewBag.Slist !=null)
{
    foreach (var item in ViewBag.Slist)
    {
        <option value="@item.Value">@item.Text</option>
    }
}



Shared Partial View
DisplayCity Partial.cshtml



@model Casdropdown.Models.city

<option value="">--Select City--</option>

@if (ViewBag.Citylist != null)
{
    foreach (var item in ViewBag.Citylist)
    {
        <option value="@item.Value">@item.Text</option>
    }
}



Model



namespace Casdropdown.Models
{
    public class Cascadingclass
    {
        public int Cid { get; set; }
        public int Sid { get; set; }
        public int Cityid { get; set; }
    }
}


Database class


public partial class city
    {
        public int Cityid { get; set; }
        public string Cityname { get; set; }
        public Nullable<int> Sid { get; set; }
    }

 public partial class country
    {
        public int Cid { get; set; }
        public string Cname { get; set; }
    }

 public partial class State
    {
        public int Sid { get; set; }
        public string Sname { get; set; }
        public Nullable<int> Cid { get; set; }
    }








Monday, June 22, 2020

linq formula in c#

public ActionResult Details(string requestid)
    {
        var entities = new EmployDBEntities1();
       var detailsModel = entities.Details.Single(e => e.Id == requestid);
       return View(detailsModel);
        //return View(entities.Details.ToList());
    }
public ActionResult Details(int countryid)
    {
list<states> statelist=db.tbl_student.where(x => x.countryid==countryid).tolist();
}
 if (search != null)
            {   
                var  model = employees.Where(x => x.Name.Contains(search) || x.Email.Contains(search)).ToList();
                return View(model);
            }

employees = employees.OrderBy(x => x.Name).ToList();


 employees = employees.OrderByDescending(x => x.Name).ToList();

Easiest way to check record is exist or not in Linq to Entity Query


 bool exist=db.UserDetails.Any(x=>x.id==1);






if you using first and first or default ......search result is same ......

but if you dont know record is present or not you must use firstordefault it will give null if record is not present ......but in first() is use ,then record not found then it will give exception in program ......so if you record is definately present so you can use first() .
UserDetail _U=db.UserDetails.where(x=>x.id==1).FirstOrDefault();
UserDetail _U=db.UserDetails.where(x=>x.id==1).First();



Sunday, June 21, 2020

html helper

<div class="field-wrap">


  @Html.TextBoxFor(model => model.Username, new { @class = "form-control", id = "SignupUsername" , placeholder = "Username", @required = "required", autofocus = "" })


  @Html.ValidationMessageFor(model => model.Username, "", new { @class = "text-danger" })
</div> 



controller::>>



  var employees = GetEmployees();
            ViewBag.categorylist = new SelectList(employees, "Id", "Name");


html

     @Html.DropDownListFor(model => model.Item2, ViewBag.categorylist as SelectList, "---SelectList--", new { onchange = "rahul()" })


crystal report in asp.net mvc

Crystalreport >> Blank report  

file explorer >> database Fields(right click) >>database Export>> Project Data>> >.Net Object>>Select your related Model and selected table >> ok

Now  database Fields >>Crystalreport.model(Fields)>>by mouse drop your fields in section3 Deatils  



cshtml


this link is given at any location on your page   


<a class="btn btn-success" href="@url.action("exportReport")">Download Report</a>




public actionresult exportReport()
{
ReportDocument rd=new reportDocument();
rd.Load(Path.Combine(Server.Mappath("-/Report"),"CrystalReport.rpt"));
rd.SetDataSource(db.Tbl_Employee.toList());
response.buffer=false;
response.ClearContent();
response.clearheader();
try
{
stream Stream =rd.Exporttostream(crystaldecision.Shared.ExportFormatType.PortableDocForma);
}
catch
{
throw;
}


}

Saturday, June 20, 2020

Javascript AJax xmlhttprequest states using code

Javascript AJax state 



let fetchBtn= document.getelementrybyid('fetchBTN');

fetchBTN.addeventlistner('click',loaDoc)
.
//if readystate = 1 mean open 2 mean send 3 mean loading 4 mean done  
function
 loadDoc() {
    var xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
            document.getElementById("demo").innerHTML =
            this.responseText;
       }
    };
    xhttp.open("GET""ajax_info.txt"true);
         xhttp.onprogress =function()
{

}



// if you want data on after on load 


         xhttp.onload function()
{

if (this.readyState == 4 && this.status == 200
{


let obj=JSON.parse(this.responseText);

let list=document.getElementrybyid('divlist');
for(ket in obj)
      {
                 str +='<li>${obj[key].employee_name}</li>';
       }
list.innerhtml= str;

}


}






    xhttp.send();
}





when you sending post request
 xhttp.open("Post""http/123.6.77.6/api/apply"true);
xhhtp.getResponseHeader('Content-Type','Json');

mydata='{name="ritesh", fname="satya", id ="67"}';
xhttp.send(myData);








other program





<script>
$(document).ready(function(){
$('#btn').click(function(){

$('#div1').load("sample.html",function(respomseTxt,statusTxt,xhr)
{
if(statusTxt=="success")

alert("all ok");
if(statusTxt=="error")
alert("Error:"+xhr.status + ":"+ xhr.statusTxt);
});
});
});
</script>



get mathod  

syntax get(url,data,callbackfunction)

$.get("samp.html","id=3",function(responseTxt,statusTxt,xhr){
$('#divid').text(responseTxt)
}).fail(function(){

}).done(function(){

})


post mathod

var data={name:"ritesh",id:"1" , fname:"rahul"}

$.post("samp.html","id=3",function(responseTxt,statusTxt,xhr){
$('#divid').text(responseTxt)
}).fail(function(){

}).done(function(){

})