Ana Sayfa / Blog Yazılarım / ASP.NET MVC BİLDİĞİM TÜM KODLAR

ASP.NET MVC BİLDİĞİM TÜM KODLAR

  • BugraSoft
  • 03/05/2024
  • 0 Yorum
  • 138 Görüntülenme

Arama kodu

Controller

public ActionResult Index(string q)

        {

            if (!string.IsNullOrEmpty(q))

 

            {

 

                ViewBag.Liste = db.IsilanlariView2

 

               .Where(b => b.IsKapsami.Contains(q) || b.CalismaYeri.Contains(q) || b.Proje.Contains(q))

 

               .OrderByDescending(x => x.ID)

 

               .ToList();

 

            }

 

            else

 

            {

 

 

                ViewBag.Liste = db.IsilanlariView2.OrderByDescending(x => x.ID).ToList();

 

            }

            ViewBag.Basvurulanlar = db.IsilanlariView2.OrderByDescending(x => x.ID).Take(5).ToList();

            return View();

        }


Html kodu

<div class="sidebar-item search-form">

                            <h3 class="sidebar-title">Ara</h3>

                            <form action="/Isler/Index" class="mt-3">

                                <input type="text" name="q">

                                <button type="submit"><i class="bi bi-search"></i></button>

                            </form>

                        </div>

 Datatable'ı excel'e aktarma kodu (parametreli)

Html Kodu

@using (Html.BeginForm("ExportToExcel3", "Admin", FormMethod.Post))

{

    <label>Seçilen İlana Başvuran Kullanıcılar</label>

    <select name="IsID" class="form-select">

        @foreach (var item in ViewBag.Ilan)

        {

            <option value="@item.ID">@item.Proje - @item.SirketUnvan</option>

        }

    </select>

    <br />

    <button type="submit" class="btn btn-success">İlanına Başvuranları Excel'e Aktar</button>

}

 

 

Controller

public ActionResult ExportToExcel3(int IsID)

        {

            try

            {

                var data = db.TumIlanViews

                                             .Where(x => x.Durumu == "A" && x.IsID == IsID)

                                             .OrderByDescending(x => x.Puan)

                                             .ThenByDescending(x => x.IsID)

                                             .ToList();

                string fileName = "IlanBasvuru_" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".xlsx";

                string filePath = Path.Combine(Server.MapPath("~/App_Data/"), fileName);

 

                // DataTable oluştur

                DataTable dataTable = new DataTable("TumCV");

                dataTable.Columns.AddRange(new DataColumn[3]

                {

                  new DataColumn("Kullanıcı No", typeof(int)),

                  new DataColumn("İlan No", typeof(int)),

                  new DataColumn("Puan", typeof(int)),

 

 

                });

 

                foreach (var item in data)

                {

                   

 

 

                    dataTable.Rows.Add(

                        item.ID,

                        item.IsID,

                        item.Puan

 

 

                    );

                }

 

                using (var workbook = new XLWorkbook())

                {

                    var worksheet = workbook.Worksheets.Add(dataTable);

                    // Sütun genişliklerini otomatik ayarla

                    worksheet.Columns().AdjustToContents();

 

                    // Dosyayı kaydet

                    workbook.SaveAs(filePath);

                }

 

                // Dosya indirme

                byte[] fileBytes = System.IO.File.ReadAllBytes(filePath);

                return File(fileBytes, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", fileName);

            }

            catch (Exception ex)

            {

                // Hata durumunda hata sayfasına yönlendir

                return RedirectToAction("Error", "Home");

            }

 

 

        }

 

Datatable'ı excel'e aktarma kodu (parametresiz)

Html Kodu

 

@using (Html.BeginForm("ExportToExcel", "Admin", FormMethod.Post))

{

    <button type="submit" class="btn btn-primary">Tümünü Excel'e Aktar</button>

}

 

 

Controller

public ActionResult ExportToExcel()

        {

            try

            {

                var data = db.TumViews.Where(x => x.Durumu == "A").OrderByDescending(x => x.Puan).ToList();

                string fileName = "TumCV_" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".xlsx";

                string filePath = Path.Combine(Server.MapPath("~/App_Data/"), fileName);

 

                // DataTable oluştur

                DataTable dataTable = new DataTable("TumCV");

                dataTable.Columns.AddRange(new DataColumn[3]

                {

                  new DataColumn("Kullanıcı No", typeof(int)),

                  new DataColumn("Puan", typeof(int)),

                  new DataColumn("Kullanıcı Adı", typeof(string)),

 

 

                });

 

                foreach (var item in data)

                {

 

                    dataTable.Rows.Add(

                        item.ID,

                        item.Puan,

                        item.KullaniciAdi

                       

                    );

                }

 

                using (var workbook = new XLWorkbook())

                {

                    var worksheet = workbook.Worksheets.Add(dataTable);

                    // Sütun genişliklerini otomatik ayarla

                    worksheet.Columns().AdjustToContents();

 

                    // Dosyayı kaydet

                    workbook.SaveAs(filePath);

                }

 

                // Dosya indirme

                byte[] fileBytes = System.IO.File.ReadAllBytes(filePath);

                return File(fileBytes, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", fileName);

            }

            catch (Exception ex)

            {

                // Hata durumunda hata sayfasına yönlendir

                return RedirectToAction("Error", "Home");

            }

 

 

        }

 

Dropdown'da veri tabanındaki veriyi seçili getirme 

Controller

ViewBag.Kisisel = db.KisiselBilgilerViews.Where(x => x.KullaniciID == ID).FirstOrDefault();

 

 

 

Html

<label for="sehir">İkamet Edilen İl</label>

 

<select class="form-select" name="SehirID" id="SehirID">

 

@foreach (var item in ViewBag.Sehirler)

{

<option value="@item.ID" @(item.SehirAdi == ViewBag.Kisisel.SehirAdi ? "selected" : "")>@item.SehirAdi</option>

}

</select>

 


2.yöntem

Html

@{

string selectedEgitimDurumuAciklama = ViewBag.Egitim.EgitimDurumuAciklama.ToString();

}

 

<h3 class="mt-3">Eğitim Durumu</h3>

<select name="EgitimDurumuAciklama" id="EgitimDurumuAciklama" style="height: 48px; padding: 10px 15px;" class="form-select">

<option value="Yüksek Lisans" @(selectedEgitimDurumuAciklama == "Yüksek Lisans" ? "selected" : "")>Yüksek Lisans (Doktora)</option>

<option value="Üniversite" @(selectedEgitimDurumuAciklama == "Üniversite" ? "selected" : "")>Üniversite</option>

<option value="Meslek YüksekOkulu" @(selectedEgitimDurumuAciklama == "Meslek YüksekOkulu" ? "selected" : "")>Meslek Yüksekokulu</option>

<option value="Lise" @(selectedEgitimDurumuAciklama == "Lise" ? "selected" : "")>Lise</option>

<option value="Çıraklık Eğitim" @(selectedEgitimDurumuAciklama == "Çıraklık Eğitim" ? "selected" : "")>Çıraklık Eğitim</option>

</select>

 

 

Dropdown'da bir seçenek seçilince altta textbox açılması

<div class="col-md-2 form-group mt-3 mt-md-0">

<label for="ilan">4. Yabancı Dil (Yazınız)</label>

<input type="text" class="form-control" name="YabanciDil4" id="YabanciDil4" />

</div>

<div class="col-md-2 form-group mt-3 mt-md-0">

<label for="ilan">Sertifika Alınan Kurum</label>

<select name="YabanciDilKurum4" id="YabanciDilKurum4" class="form-select" onchange="toggleInput()">

 <option value="">Seçiniz</option>

 <option value="TELC">TELC</option>

 <option value="GOETHE">GOETHE</option>

 <option value="OSD">OSD</option>

<option value="Diğer">Diğer</option>

</select>

 <br />

<input name="YabanciDilKurum41" id="YabanciDilKurum41" style="display: none;" class="form-control" placeholder="Kurum Adı Giriniz"/>

 <script>

function toggleInput() {

var selectBox = document.getElementById("YabanciDilKurum4");

var otherInput = document.getElementById("YabanciDilKurum41");

 

if (selectBox.value === "Diğer") {

                                        otherInput.style.display = "block";

selectBox.name = "YabanciDilKurum41"; // select'in name özelliğini değiştirme

otherInput.name = "YabanciDilKurum4"; // input'un name özelliğini değiştirme

 } else {

                                        otherInput.style.display = "none";

selectBox.name = "YabanciDilKurum4"; // select'in name özelliğini eski haline getirme

otherInput.name = "YabanciDilKurum41"; // input'un name özelliğini eski haline getirme

}

}

</script>

</div>

 

 Giriş ve kayıt yapma MD-5 ile

Giriş Yapma

 

public ActionResult Index()

        {

            return View();

 

        }

 

        [HttpPost]

        public ActionResult Index(Kullanicilar kullanicilar, string parola)

        {

            var s = Crypto.Hash(parola, "MD5");

            var l = db.Kullanicilars.FirstOrDefault(x => x.KullaniciAdi == kullanicilar.KullaniciAdi);

            if (l != null && l.Parola == s)

            {

                Session["KullaniciID"] = l.ID;

                Session["KullaniciAdi"] = l.KullaniciAdi;

                Session["CvDoluMu"] = l.CVDoluMu;

 

                var kb1 = db.KisiselBilgilers.FirstOrDefault(k => k.KullaniciID == l.ID);

                if (kb1 == null)

                {

                    return RedirectToAction("Index", "CV");

                }else

                {

                    return RedirectToAction("Index", "Isler");

                }

 

               

            }

 

  

Kayıt Olma

 

     public ActionResult Index()

        {

            return View();

        }

 

        [HttpPost]

        [ValidateAntiForgeryToken]

        public ActionResult Index(Kullanicilar kullanicilar, string KullaniciAdi, string parola)

        {

 

            if (ModelState.IsValid)

            {

                var kullanicivarmi = db.Kullanicilars.FirstOrDefault(x => x.KullaniciAdi == kullanicilar.KullaniciAdi);

 

                if (kullanicivarmi == null)

                {

                    kullanicilar.Parola = Crypto.Hash(parola, "MD5");

                    kullanicilar.Durumu = "A";

                    kullanicilar.CVDoluMu = "H";

                    db.Kullanicilars.Add(kullanicilar);

                    db.SaveChanges();

                    var l = db.Kullanicilars.Where(x => x.KullaniciAdi == kullanicilar.KullaniciAdi).SingleOrDefault();

                    Session["KullaniciID"] = l.ID;

                    Session["KullaniciAdi"] = l.KullaniciAdi;

                    Session["CvDoluMu"] = l.CVDoluMu;

                    return RedirectToAction("Index", "CV");

                }

 

                ViewBag.Uyari = "Bu kullanıcı adı zaten kullanılıyor.";

                return View();

 

            }

 

            return View();

 

 

 

        }

 

Aynı sayfa ismine yönlendirirsek şu kodu yazarsak mesaj yansıtabiliriz

@if (!string.IsNullOrEmpty(ViewBag.Uyari))

                            {

 

                                <p class="text-danger text-center"> @ViewBag.Uyari</p>

 

                            }

 

 


BAYRAKLI SİTE DİL ÇEVİRME KODU (TRANSLATE APİ)

Css kodları


<style>

       

        .ct-topbar {

            text-align: right;

            background: #eee;

        }

 

        .ct-topbar__list {

            margin-bottom: 0px;

        }

 

        .ct-language__dropdown {

            padding-top: 8px;

            max-height: 0;

            overflow: hidden;

            position: absolute;

            top: 110%;

            left: -3px;

            -webkit-transition: all 0.25s ease-in-out;

            transition: all 0.25s ease-in-out;

            width: 100px;

            text-align: center;

            padding-top: 0;

            z-index: 200;

        }

 

            .ct-language__dropdown li {

                background: #222;

                padding: 5px;

            }

 

                .ct-language__dropdown li a {

                    display: block;

                }

 

                .ct-language__dropdown li:first-child {

                    padding-top: 10px;

                    border-radius: 3px 3px 0 0;

                }

 

                .ct-language__dropdown li:last-child {

                    padding-bottom: 10px;

                    border-radius: 0 0 3px 3px;

                }

 

                .ct-language__dropdown li:hover {

                    background: #444;

                }

 

            .ct-language__dropdown:before {

                content: '';

                position: absolute;

                top: 0;

                left: 0;

                right: 0;

                margin: auto;

                width: 8px;

                height: 0;

                border: 0 solid transparent;

                border-right-width: 8px;

                border-left-width: 8px;

                border-bottom: 8px solid #222;

            }

 

        .ct-language {

            position: relative;

            background: #00aced;

            color: #fff;

            padding: 10px 0;

        }

 

            .ct-language:hover .ct-language__dropdown {

                max-height: 200px;

                padding-top: 8px;

            }

 

        .list-unstyled {

            padding-left: 0;

            list-style: none;

        }

 

        /* Additional styles to hide Google Translate banner and logo */

 

        .goog-te-banner-frame.skiptranslate {

            display: none !important;

        }

 

        .goog-te-gadget .goog-te-combo {

            display: none !important;

        }

 

        .goog-te-gadget .goog-te-gadget-icon {

            background: none !important;

        }

 

        .goog-logo-link {

            display: none !important;

        }

 

        .lang-check-unvisible {

            visibility: hidden;

        }

 

        #google_translate_element {

            float: left; /* Float the google_translate_element to the left */

        }

 

        #flag-holder {

            float: left; /* Float the flag-holder to the left */

            margin-left: 10px; /* Adjust the margin between google_translate_element and flag-holder */

        }

    </style>

 

 

HTML KODLARI

<div class="row">

 

                <!-- Bayrak -->

                <div class="col-lg-4 col-md-3 col-sm-2">

 

                    <div id="flag-holder" class="">

                    </div>

 

                </div>

                <!-- Dil Seçimi -->

                <div class="col-lg-8 col-md-6 col-sm-4">

                    <div id="google_translate_element" class="md-2">

                    </div>

                </div>

</div>

 

 

 

 

<div id="language_check" class="lang-check-unvisible">

        <span class="lang-check-unvisible">Giriş Yap</span>

</div>

 

 

 

 

<script type="text/javascript">

        function googleTranslateElementInit() {

            var translator = new google.translate.TranslateElement({

                pageLanguage: 'tr',

                includedLanguages: 'tr,en,de',

                layout: google.translate.TranslateElement.InlineLayout.SIMPLE,

                autoDisplay: false,

                gaTrack: true,

                gaId: 'UA-123456789-1'

            }, 'google_translate_element');

 

            // Wait for the translation to be fully loaded

            google.translate.TranslateService.getInstance().onAfterTranslate.subscribe(function (event) {

                var language = event.translateLanguage;

                if (language !== 'de') {

                    console.log('User is likely using translator.');

                    // Here you can perform any action you want

                }

            });

        }

    </script>

 

 

    <script type="text/javascript" src="//translate.google.com/translate_a/element.js?cb=googleTranslateElementInit"></script>

 

    <script>

        function updateFlag() {

            var languageCheck = document.getElementById('language_check');

            var flagHolder = document.getElementById('flag-holder');

            var text = languageCheck.textContent.trim();

 

            if (text === "Giriş Yap") {

                flagHolder.innerHTML = '<img src="https://flagicons.lipis.dev/flags/4x3/tr.svg" width="32px" />';

            } else if (text === "Anmeldung") {

                flagHolder.innerHTML = '<img src="https://flagicons.lipis.dev/flags/4x3/de.svg" width="32px" />';

            } else if (text === "Se connecter") {

                flagHolder.innerHTML = '<img src="https://flagicons.lipis.dev/flags/4x3/fr.svg" width="32px" />';

            } else if (text === "Login") {

                flagHolder.innerHTML = '<img src="https://flagicons.lipis.dev/flags/4x3/gb.svg" width="32px" />';

            }

        }

 

        // Initial update

        updateFlag();

 

        // Event listener for changes in the text content

        var languageCheck = document.getElementById('language_check');

        languageCheck.addEventListener('DOMSubtreeModified', updateFlag);

    </script>

 

    <script>

        // Function to hide the iframe

        function hideIframe() {

            var iframe = document.getElementById(':2.container');

            if (iframe) {

                iframe.style.display = 'none';

            }

        }

 

        // Call the function to hide the iframe initially

        hideIframe();

 

        // Use MutationObserver to continuously monitor changes in the DOM

        var observer = new MutationObserver(function (mutations) {

            mutations.forEach(function (mutation) {

                hideIframe(); // Call the function to hide the iframe whenever a mutation occurs

            });

        });

 

        // Configuration of the MutationObserver

        var config = { childList: true, subtree: true };

 

        // Start observing the target node for configured mutations

        observer.observe(document.body, config);

 

    </script>

 

 

PDF YÜKLEME


html

<form action="/CV/Index" method="post" enctype="multipart/form-data" role="form" class="cvcss">

                    <div class="row mt-3">

                        @Html.AntiForgeryToken()

                       

                        <input type="hidden" name="KullaniciID" value="@Session["KullaniciID"]" />

                       

 

                        <div class="col-md-4 form-group mt-3 mt-md-0">

                            <label for="ilan">Diplomanız</label>

                            <input type="file" name="MezuniyetDiploma" style="height: 48px; padding: 10px 15px;" class="form-control" id="MezuniyetDiploma">

                        </div>

</form>

 

 

Controller

public ActionResult Index(EgitimDurumu ed){

 

string uploadsFolder = Server.MapPath("~/Uploads");

if (MezuniyetDiploma != null && MezuniyetDiploma.ContentLength > 0)

                    {

                        string fileName = Guid.NewGuid().ToString() + Path.GetExtension(MezuniyetDiploma.FileName);

                        string path = Path.Combine(uploadsFolder, fileName);

                        MezuniyetDiploma.SaveAs(path);

                        ed.MezuniyetDiploma = fileName;

     }

db.EgitimDurumus.Add(ed);

db.SaveChanges();

ViewBag.Bilgi = "Başarılı";

return View();

}

 

 

TOPLU PDF YÜKLEME

<form action="/CV/Index" method="post" enctype="multipart/form-data" role="form" class="cvcss">

                    <div class="row mt-3">

                        @Html.AntiForgeryToken()

                       

                        <input type="hidden" name="KullaniciID" value="@Session["KullaniciID"]" />

                       

 

    <label for="SertifikaAdi1">Tüm Sertifikalarınızı Yükleyebilirsiniz.</label>

 <input type="file" name="SertifikaBelgeler" class="form-control" id="SertifikaBelge" multiple>

</form>

 

 

CONTROLLER

Public ActionResult Index(HttpPostedFileBase[] SertifikaBelgeler, Sertifikalar sert){

string uploadsFolder = Server.MapPath("~/Uploads");

foreach (var file in SertifikaBelgeler)

                    {

                        if (file != null && file.ContentLength > 0)

                        {

                            // Dosya adını oluştur

                            string fileName = Guid.NewGuid().ToString() + Path.GetExtension(file.FileName);

                            string path = Path.Combine(uploadsFolder, fileName);

 

                            // Dosyayı kaydet

                            file.SaveAs(path);

 

                            // Veritabanına kaydetme işlemleri

                            Sertifikalar sertifika = new Sertifikalar

                            {

                                SertifikaBelgeler = fileName,

                                KullaniciID = KullaniciID

                            };

                            db.Sertifikalars.Add(sertifika);

                        }

                    }

db.SaveChanges();

ViewBag.Bilgi = "Başarılı";

return View();

 

}

 

 

RESİM YÜKLEME

 

controller

[HttpPost]

        [ValidateAntiForgeryToken]

        [ValidateInput(false)]

        public ActionResult IlanEkle(Isilanlari2 s, HttpPostedFileBase ResimURL)

        {

            ViewBag.Isverenler = db.Isverenlers.Where(x => x.Durumu == "A").ToList();

            WebImage img = new WebImage(ResimURL.InputStream); //bu ikisi resim ekleme

            FileInfo imginfo = new FileInfo(ResimURL.FileName);

 

            string logoname = Guid.NewGuid().ToString() + imginfo.Extension; //resim adlandırma

            img.Resize(1024, 768);  // resim boyutu

            img.Save("~/resim/" + logoname);

 

            s.ResimURL = "/resim/" + logoname;

            s.IlanDurum = "A";

            db.Isilanlari2.Add(s);

            db.SaveChanges();

            return View();

 

 

        }

 

 

SESSİON SÜRESİ UZATMA

Controller’a bunu yaz

 

protected override void OnActionExecuting(ActionExecutingContext filterContext)

        {

            base.OnActionExecuting(filterContext);

 

            // Oturum süresini güncelle

            HttpContext.Session.Timeout = 60; // Örnek olarak 60 dakika

        }

 

 

Global.Asax dosyasına bunu yaz

protected void Session_Start(object sender, EventArgs e)

        {

            // Oturum süresini 60 dakika olarak ayarla

            Session.Timeout = 60;

        }

 


VERİ TABANINDAKİ DEĞERE GÖRE RADİOBUTTON SEÇİLİ GETİRME

<div class="form-check">

<input class="form-check-input" type="radio" id="KronikYok" name="KronikDurum" value="YOK" @(ViewBag.Saglik.KronikDurum == "YOK" ? "checked" : "")>

<label class="form-check-label" for="KronikYok">YOK</label>

</div>

 

<div class="form-check">

<input class="form-check-input" type="radio" id="KronikVar" name="KronikDurum" value="VAR" @(ViewBag.Saglik.KronikDurum == "VAR" ? "checked" : "")>

<label class="form-check-label" for="KronikVar">VAR</label>

</div>

 

 VERİ TABANINDAKİ DEĞERE GÖRE TARİH SEÇİLİ GETİRME

Controller

ViewBag.Kisisel = db.KisiselBilgilerViews.Where(x => x.KullaniciID == ID).FirstOrDefault();



HTML

@{

            DateTime dogum = Convert.ToDateTime(ViewBag.Kisisel.DogumTarihi.ToString("dd.MM.yyyy"));

            string dogumTarihiString = dogum.ToString("yyyy-MM-dd");

 

}

 

<div class="col-md-6 form-group mt-3 mt-md-0">

<label for="dogum">Doğum Tarihiniz</label>

<input type="date" class="form-control" name="DogumTarihi" value="@dogumTarihiString" id="dogum" style="height: 48px; padding: 10px 15px;">

</div>



VERİ TABANINDAKİ VERİLERİ DROPDOWN'A AKTARMA

Controller

 

  public ActionResult Index()

        {

            ViewBag.Nace2 = db.KodNaces.OrderBy(x => x.Tanim).ToList();

            return View();

 

        }

 

 Html

<label for="MeslekNaceKod">Nace Kodu</label>

<select id="MeslekNaceKod" name="MeslekNaceKod"     style="height: 48px; padding: 10px 15px;" class="form-select">

<option value="">Seçiniz</option>

@foreach (var item in ViewBag.Nace2)

    {

  <option value="@item.ID"> @item.Tanim - @item.Kod </option>

  }

</select>

 

YÜKLÜ VERİDE ZAMAN AŞIMINA UĞRAMAMASI İÇİN

Web Config’e şunu yaz

<system.web>

    <compilation debug="true" targetFramework="4.8" />

    <httpRuntime targetFramework="4.8" maxRequestLength="2147483647" executionTimeout="3600" />

      

  </system.web>

 

 



Yorumlar

henüz yorum bulunamadı

Yorum Yap