evren pehlivan yazılım,
evren pehlivan yazılım geliştirici
evren pehlivan
evren pehlivan blog
14 Aralık 2019 Cumartesi
16 Eylül 2019 Pazartesi
Getting address of value or reference
public static class AddressHelper
{
private static object mutualObject;
private static ObjectReinterpreter reinterpreter;
static AddressHelper()
{
AddressHelper.mutualObject = new object();
AddressHelper.reinterpreter = new ObjectReinterpreter();
AddressHelper.reinterpreter.AsObject = new ObjectWrapper();
}
public static IntPtr GetAddress(object obj)
{
lock (AddressHelper.mutualObject)
{
AddressHelper.reinterpreter.AsObject.Object = obj;
IntPtr address = AddressHelper.reinterpreter.AsIntPtr.Value;
AddressHelper.reinterpreter.AsObject.Object = null;
return address;
}
}
public static T GetInstance<T>(IntPtr address)
{
lock (AddressHelper.mutualObject)
{
AddressHelper.reinterpreter.AsIntPtr.Value = address;
return (T)AddressHelper.reinterpreter.AsObject.Object;
}
}
// I bet you thought C# was type-safe.
[System.Runtime.InteropServices.StructLayout(System.Runtime.InteropServices.LayoutKind.Explicit)]
private struct ObjectReinterpreter
{
[System.Runtime.InteropServices.FieldOffset(0)] public ObjectWrapper AsObject;
[System.Runtime.InteropServices.FieldOffset(0)] public IntPtrWrapper AsIntPtr;
}
private class ObjectWrapper
{
public object Object;
}
private class IntPtrWrapper
{
public IntPtr Value;
}
}
{
private static object mutualObject;
private static ObjectReinterpreter reinterpreter;
static AddressHelper()
{
AddressHelper.mutualObject = new object();
AddressHelper.reinterpreter = new ObjectReinterpreter();
AddressHelper.reinterpreter.AsObject = new ObjectWrapper();
}
public static IntPtr GetAddress(object obj)
{
lock (AddressHelper.mutualObject)
{
AddressHelper.reinterpreter.AsObject.Object = obj;
IntPtr address = AddressHelper.reinterpreter.AsIntPtr.Value;
AddressHelper.reinterpreter.AsObject.Object = null;
return address;
}
}
public static T GetInstance<T>(IntPtr address)
{
lock (AddressHelper.mutualObject)
{
AddressHelper.reinterpreter.AsIntPtr.Value = address;
return (T)AddressHelper.reinterpreter.AsObject.Object;
}
}
// I bet you thought C# was type-safe.
[System.Runtime.InteropServices.StructLayout(System.Runtime.InteropServices.LayoutKind.Explicit)]
private struct ObjectReinterpreter
{
[System.Runtime.InteropServices.FieldOffset(0)] public ObjectWrapper AsObject;
[System.Runtime.InteropServices.FieldOffset(0)] public IntPtrWrapper AsIntPtr;
}
private class ObjectWrapper
{
public object Object;
}
private class IntPtrWrapper
{
public IntPtr Value;
}
}
15 Kasım 2018 Perşembe
Thread Safe File Writing in C# (Wait On Lock) ReaderWriterLockSlim
public class Demo {
private static ReaderWriterLockSlim _readWriteLock = new ReaderWriterLockSlim();
public void WriteToFileThreadSafe(string text, string path) {
// Set Status to Locked
_readWriteLock.EnterWriteLock();
try
{
// Append text to the file
using (StreamWriter sw = File.AppendText(path))
{
sw.WriteLine(text);
sw.Close();
}
}
finally
{
// Release lock
_readWriteLock.ExitWriteLock();
}
}
}
Kaynak: http://www.johandorper.com/log/thread-safe-file-writing-csharpReklam: www.evrenpehlivan.com
30 Ekim 2018 Salı
fluentvalidation.net entity validation
public class CustomerValidator : AbstractValidator<Customer> {
public CustomerValidator() {
RuleFor(x => x.Surname).NotEmpty();
RuleFor(x => x.Forename).NotEmpty().WithMessage("Please specify a first name");
RuleFor(x => x.Discount).NotEqual(0).When(x => x.HasDiscount);
RuleFor(x => x.Address).Length(20, 250);
RuleFor(x => x.Postcode).Must(BeAValidPostcode).WithMessage("Please specify a valid postcode");
}
private bool BeAValidPostcode(string postcode) {
// custom postcode validating logic goes here
}
}
https://fluentvalidation.net/Solid prensiplere uygun validation için attribute validation yerine kullanılabilecek kütüphane.
.When(x => x.HasDiscount);
21 Eylül 2018 Cuma
JS Validation
@model WebTimeSheetManagement.Models.Registration
@using CaptchaMvc.HtmlHelpers
@{
ViewBag.Title = "CreateAdmin";
Layout = "~/Views/Shared/_LayoutSuperAdmin.cshtml";
}
<h4 class="page-header">Create Admin User</h4>
<div class="panel panel-default">
<div class="panel-heading">Create Admin User</div>
<div class="panel-body">
@if (TempData["MessageRegistration"] != null)
{
<p class="alert alert-success" id="successMessage">@TempData["MessageRegistration"]</p>
}
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
@using (Html.BeginForm("CreateAdmin", "SuperAdmin"))
{
@Html.AntiForgeryToken()
<div class="row">
<div class="col-lg-4">
@Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label manadatory" })
@Html.TextBoxFor(model => model.Name, new { @class = "form-control", @maxlength = 40, @onkeypress = "return onlyspecchar(event);" })
@Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })
</div>
<div class="col-lg-4">
@Html.LabelFor(model => model.Mobileno, htmlAttributes: new { @class = "control-label manadatory" })
@Html.TextBoxFor(model => model.Mobileno, new { @class = "form-control", @maxlength = 10, @onkeydown = "return OnlyNumeric(this);" })
@Html.ValidationMessageFor(model => model.Mobileno, "", new { @class = "text-danger" })
</div>
<div class="col-lg-4">
@Html.LabelFor(model => model.EmailID, htmlAttributes: new { @class = "control-label manadatory" })
@Html.TextBoxFor(model => model.EmailID, new { @class = "form-control", @maxlength = 50 })
@Html.ValidationMessageFor(model => model.EmailID, "", new { @class = "text-danger" })
</div>
</div>
<div class="row">
<div class="col-lg-4" style="margin-top:20px;">
@Html.LabelFor(model => model.Gender, htmlAttributes: new { @class = "control-label manadatory" })
@Html.RadioButtonFor(model => model.Gender, "M") @Html.Label("", "Male")
@Html.RadioButtonFor(model => model.Gender, "F") @Html.Label("", "Female")
<br />
@Html.ValidationMessageFor(model => model.Gender, "", new { @class = "text-danger" })
</div>
<div class="col-lg-4">
@Html.LabelFor(model => model.Birthdate, htmlAttributes: new { @class = "control-label" })
@Html.TextBoxFor(model => model.Birthdate, new { @class = "form-control", @onkeypress = "alert('Choose Birthdate');" })
@Html.ValidationMessageFor(model => model.Birthdate, "", new { @class = "text-danger" })
</div>
<div class="col-lg-4">
</div>
</div>
<div class="row">
<div class="col-lg-4">
@Html.LabelFor(model => model.Username, htmlAttributes: new { @class = "control-label manadatory" })
@Html.TextBoxFor(model => model.Username, new { @class = "form-control", @maxlength = 20, @onkeypress = "return onlyspecchar(event);", @onblur = "CheckUsernameExists();" })
@Html.ValidationMessageFor(model => model.Username, "", new { @class = "text-danger" })
</div>
<div class="col-lg-4">
@Html.LabelFor(model => model.Password, htmlAttributes: new { @class = "control-label manadatory" })
@Html.PasswordFor(model => model.Password, new { @class = "form-control", @maxlength = 30, })
@Html.ValidationMessageFor(model => model.Password, "", new { @class = "text-danger" })
</div>
<div class="col-lg-4">
@Html.LabelFor(model => model.ConfirmPassword, htmlAttributes: new { @class = "control-label manadatory" })
@Html.PasswordFor(model => model.ConfirmPassword, new { @class = "form-control" })
@Html.ValidationMessageFor(model => model.ConfirmPassword, "", new { @class = "text-danger" })
</div>
</div>
<br />
<div class="row">
<div class="form-group">
<div class="col-md-10">
<input type="submit" value="Create Admin" class="btn btn-success" />
@Html.ActionLink("Clear", "CreateAdmin", "SuperAdmin", null, new { @class = "btn btn-danger" })
@Html.ActionLink("All Admin", "admin", "AllUsers", null, new { @class = "btn btn-info" })
</div>
</div>
</div>
}
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
$("#Birthdate").datepicker
({
dateFormat: "yy-mm-dd",
changeMonth: true,
changeYear: true,
yearRange: "-100:+100",
onSelect: function (date) {
var dob = new Date(date);
var today = new Date();
if (dob.getFullYear() + 18 < today.getFullYear()) {
}
else {
$("#Birthdate").val('');
alert("You are not eligible for Registration");
}
}
});
});
function OnlyNumeric(evt) {
var charCode = (evt.which) ? evt.which : evt.keyCode
if ((charCode < 48 || charCode > 57)) {
if (charCode == 8 || charCode == 46 || charCode == 0) {
return true;
}
else {
return false;
}
}
}
function CheckUsernameExists() {
var url = '@Url.Content("~/")' + "Registration/CheckUserNameExists";
var source = "#Username";
$.post(url, { Username: $(source).val() }, function (data) {
if (data) {
$(source).val('');
alert("Username Already Used try unique one!");
}
else {
}
});
}
function onlyspecchar(evt) {
var charCode = (evt.which) ? evt.which : evt.keyCode
var txt = String.fromCharCode(charCode)
if ((txt.match(/^[a-zA-Z\b. ]+$/)) || (txt.match(/^[0-9]+$/)) || (charCode == 64) || (charCode == 45) || (charCode == 46) || (charCode == 95) || (charCode == 41)) {
return true;
}
return false;
}
</script>
@using CaptchaMvc.HtmlHelpers
@{
ViewBag.Title = "CreateAdmin";
Layout = "~/Views/Shared/_LayoutSuperAdmin.cshtml";
}
<h4 class="page-header">Create Admin User</h4>
<div class="panel panel-default">
<div class="panel-heading">Create Admin User</div>
<div class="panel-body">
@if (TempData["MessageRegistration"] != null)
{
<p class="alert alert-success" id="successMessage">@TempData["MessageRegistration"]</p>
}
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
@using (Html.BeginForm("CreateAdmin", "SuperAdmin"))
{
@Html.AntiForgeryToken()
<div class="row">
<div class="col-lg-4">
@Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label manadatory" })
@Html.TextBoxFor(model => model.Name, new { @class = "form-control", @maxlength = 40, @onkeypress = "return onlyspecchar(event);" })
@Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })
</div>
<div class="col-lg-4">
@Html.LabelFor(model => model.Mobileno, htmlAttributes: new { @class = "control-label manadatory" })
@Html.TextBoxFor(model => model.Mobileno, new { @class = "form-control", @maxlength = 10, @onkeydown = "return OnlyNumeric(this);" })
@Html.ValidationMessageFor(model => model.Mobileno, "", new { @class = "text-danger" })
</div>
<div class="col-lg-4">
@Html.LabelFor(model => model.EmailID, htmlAttributes: new { @class = "control-label manadatory" })
@Html.TextBoxFor(model => model.EmailID, new { @class = "form-control", @maxlength = 50 })
@Html.ValidationMessageFor(model => model.EmailID, "", new { @class = "text-danger" })
</div>
</div>
<div class="row">
<div class="col-lg-4" style="margin-top:20px;">
@Html.LabelFor(model => model.Gender, htmlAttributes: new { @class = "control-label manadatory" })
@Html.RadioButtonFor(model => model.Gender, "M") @Html.Label("", "Male")
@Html.RadioButtonFor(model => model.Gender, "F") @Html.Label("", "Female")
<br />
@Html.ValidationMessageFor(model => model.Gender, "", new { @class = "text-danger" })
</div>
<div class="col-lg-4">
@Html.LabelFor(model => model.Birthdate, htmlAttributes: new { @class = "control-label" })
@Html.TextBoxFor(model => model.Birthdate, new { @class = "form-control", @onkeypress = "alert('Choose Birthdate');" })
@Html.ValidationMessageFor(model => model.Birthdate, "", new { @class = "text-danger" })
</div>
<div class="col-lg-4">
</div>
</div>
<div class="row">
<div class="col-lg-4">
@Html.LabelFor(model => model.Username, htmlAttributes: new { @class = "control-label manadatory" })
@Html.TextBoxFor(model => model.Username, new { @class = "form-control", @maxlength = 20, @onkeypress = "return onlyspecchar(event);", @onblur = "CheckUsernameExists();" })
@Html.ValidationMessageFor(model => model.Username, "", new { @class = "text-danger" })
</div>
<div class="col-lg-4">
@Html.LabelFor(model => model.Password, htmlAttributes: new { @class = "control-label manadatory" })
@Html.PasswordFor(model => model.Password, new { @class = "form-control", @maxlength = 30, })
@Html.ValidationMessageFor(model => model.Password, "", new { @class = "text-danger" })
</div>
<div class="col-lg-4">
@Html.LabelFor(model => model.ConfirmPassword, htmlAttributes: new { @class = "control-label manadatory" })
@Html.PasswordFor(model => model.ConfirmPassword, new { @class = "form-control" })
@Html.ValidationMessageFor(model => model.ConfirmPassword, "", new { @class = "text-danger" })
</div>
</div>
<br />
<div class="row">
<div class="form-group">
<div class="col-md-10">
<input type="submit" value="Create Admin" class="btn btn-success" />
@Html.ActionLink("Clear", "CreateAdmin", "SuperAdmin", null, new { @class = "btn btn-danger" })
@Html.ActionLink("All Admin", "admin", "AllUsers", null, new { @class = "btn btn-info" })
</div>
</div>
</div>
}
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
$("#Birthdate").datepicker
({
dateFormat: "yy-mm-dd",
changeMonth: true,
changeYear: true,
yearRange: "-100:+100",
onSelect: function (date) {
var dob = new Date(date);
var today = new Date();
if (dob.getFullYear() + 18 < today.getFullYear()) {
}
else {
$("#Birthdate").val('');
alert("You are not eligible for Registration");
}
}
});
});
function OnlyNumeric(evt) {
var charCode = (evt.which) ? evt.which : evt.keyCode
if ((charCode < 48 || charCode > 57)) {
if (charCode == 8 || charCode == 46 || charCode == 0) {
return true;
}
else {
return false;
}
}
}
function CheckUsernameExists() {
var url = '@Url.Content("~/")' + "Registration/CheckUserNameExists";
var source = "#Username";
$.post(url, { Username: $(source).val() }, function (data) {
if (data) {
$(source).val('');
alert("Username Already Used try unique one!");
}
else {
}
});
}
function onlyspecchar(evt) {
var charCode = (evt.which) ? evt.which : evt.keyCode
var txt = String.fromCharCode(charCode)
if ((txt.match(/^[a-zA-Z\b. ]+$/)) || (txt.match(/^[0-9]+$/)) || (charCode == 64) || (charCode == 45) || (charCode == 46) || (charCode == 95) || (charCode == 41)) {
return true;
}
return false;
}
</script>
28 Ağustos 2018 Salı
Note Defteri Varsayılan Kaydetme Formatını Değiştirme
Default UTF-8 encoding for new Notepad documents
Short of using a third party editor, is there a way to configure Notepad so that new documents are automatically saved in Unicode without having to change manually the encoding every single time from default ANSI to UTF-8?Typical scenario:
- Start typing some text with no extended characters
- Save the file: It is automatically in ANSI
- Open the file again to edit, add some extended characters, save again:
Notepad tells you the extended characters will be lost if you confirm the save operation.
At least that last message offers the possibility to backup and "Save as" to choose UTF-8, but 1) this is very cumbersome, and 2) files with no extended characters will still be saved in ANSI by default.
Windows won't really be fully Unicode if the default Notepad encoding is still the obsolete ANSI code page, but, even if I reluctantly admit changing default behaviors is tricky for compatibility reasons, there should at least be a user option to select the default encoding for new documents, like other third party editors offer, such as Notepad++.
Currently, Windows forces me to replace Notepad file associations to use other text editors. Not a bad thing given the poor set of features in Notepad, but it would have been great to have this option in the standard O.S.
This thread is locked. You can follow the question or vote as helpful, but you cannot reply to this thread. I have the same question (208)
Question Info
Last updated August 28, 2018
Views 163,222
Applies to:
Windows Windows 7 / Programs
Image Answer
MA
Maneuver Replied on May 12, 2010
ReplyIn reply to Chimel's post on May 4, 2010
1. Right click -> New -> Text Document
2. Open "New Text Document.txt". Do NOT type anything!
3. Go to "File -> Save As... " and choose UTF-8 under "Encoding:", press "Save" and overwrite existing file. Close the file.
4. Rename "New Text Document.txt" to "TXTUTF-8.txt"
5. Copy "TXTUTF-8.txt" to "C:\WINDOWS\SHELLNEW"
6. Go to "Start -> Run..." and type
---------
regedit
---------
Press OK.
7. Navigate to
-------------------------------------------
HKEY_CLASSES_ROOT\.txt\ShellNew
-------------------------------------------
8. Right click in the right window -> New -> "String Value" and rename it to
-----------
FileName
-----------
9. Double click on "FileName" and put
----------------
TXTUTF-8.txt
----------------
into "Value data:" field and press OK.
10. It's finished.
11. Test it: Create new .txt document (Right click -> New -> Text Document). Open it and go to "File -> Save As... " and see that encoding is set by default to UTF-8 . :-)
Credits go to Robert Clemenzi and his explanation of "FileName" string (and its linkage with "Template directory") within registry:
http://mc-computing.com/WinExplorer/WinExplorerRegistry_ShellNew.htm
NOTE: These steps are ONLY for creating new and blank UTF-8 .txt documents. If .txt is already saved with ANSI encoding, it will stay ANSI when saving it next time - so if UTF-8 is needed (in this case), it must be set manually.
P.S. Also change "fSavePageSettings" & "fSaveWindowPositions" DWORD values to "1" within following registry key:
HKEY_CURRENT_USER\Software\Microsoft\Notepad
Info: http://www.pc1news.com/saving-changes-to-notepad-configuration-1216.html
evrenpehlivan.com
evren pehlivan
16 Ağustos 2018 Perşembe
Loader on Form Submit using JQuery and Ajax
As we all know, users are impatient. We also know that if we don’t tell them our application is “doing something” they tend to do silly things like click the mouse repeatedly, seeking some sign that the requested action is indeed being performed.
For this reason, it is a good idea to throw up some sort of “busy” indicator when a user-initiated action may invoke a long-running process which requires them to wait.
In this article we are going to demonstrate a very basic way to achieve this which will be effective in most cases.
If you are new to ASP.NET MVC, you may want to check out my previous posts on Routing Basics and Route Customization as well. While not critical to understanding what we discuss here, some background on the basics of MVC routing will certainly help in understanding what’s going on in places.
The fully-functioning source code for the example used in this article is available from my Github Repo. You will need to use Nuget Package Restore to pull down all the package goodness so that the project will run. If you are unsure what that means, see Keep Nuget Packages Out of Source Control with Nuget Package Manager Restore.
- Get the Example Code from Github
- Adding a Busy Indicator to a Page with JQuery and Ajax
- Basic Example – The View
- Basic Example – The Controller
- Get a Busy Indicator GIF
- The View, with Animated GIF and Placeholder for Submission Result
- Adding the Ajax Request
- Additional Resources and Items of Interest
What the Hell is Ajax?
Ajax is an acronym for Asynchronous JavaScript and XML. Ajax represents a broad range of technologiesused to facilitate client-server communication without interfering with the current state of the page.
In the main, we most often use the term when we speak of making an Ajax Request to the server, usually in the context of posting or retrieving data, and updating only a portion of the page, as opposed to completely refreshing a page simply because a small sub-area needs to be updated.
Upon the introduction of the term circa 2005, XML represented what many believed would be the primary data interchange format for this type of client-server transaction. Since then, JavaScript Object Notation (JSON) has become more and more of a standard. While XML is not gone, you are as likely to send and receive JSON in the course of an Ajax request as you are XML.
At present, we often find Ajax used in conjunction with JQuery (more properly, one often uses JQuery to make an Ajax request) when we need to retain the current state of our page while a request is made to the server and then update the portion of the page affected by the information returned from the request.
Adding a Busy indicator to a Page with JQuery and Ajax
The common way to display a busy indicator on a page while we wait for a long-running request to return from the server is to throw up an animated Gif, to let users know something is in fact happening. Equally as often, we need to then remove or hide the animation when the process completes, and refresh the portion of the page affected by our new data.
There really is no good way to do this from the server side in an MVC application – we need to use Ajax. We do this with JavaScript. in this case, we are going to use the popular JQuery library, because it is ubiquitous, it ships with and in integrated into the core MVC project.
Let’s take a look at a quick example.
Basic Example – The View
First we will look at a basic view. We’ve kept it simple here – we will display a couple of data entry fields, and a button to submit the data entered by the user. The essential cshtml code for this is as follows:
A Basic View:
@model JqueryBusyExample.Models.DemoViewModel
@{
ViewBag.Title = "Home Page";
}
<h3>Enter Your Name and Submit:</h3>
@using (Html.BeginForm("LongRunningDemoProcess",
"Home", FormMethod.Post,
new { encType = "multipart/form-data", id="myform", name = "myform" }))
{
<div class="form-group">
@Html.LabelFor(model => model.FirstName,
new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.FirstName)
@Html.ValidationMessageFor(model => model.FirstName)
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.LastName,
new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.LastName)
@Html.ValidationMessageFor(model => model.LastName)
</div>
</div>
<input type="submit" name="operation" id="process" value="process" />
}
As we can see, there is nothing unusual here. We use standard Razor syntax to create a form with a couple data entry fields for First and Last names, and a submit button. In the opening of the
using
statement, The form is wired to a method named LongRunningDemoProcess
on our HomeController
.
In the form declaration, the syntax is:
Html.BeginForm(<actionName>, <controllerName>, <Http Method Type>, <Html Attributes>)
The above basically determines what happens when the form is submitted, and specifies a specific method, and a specific controller as a target for the Http request. It also defines the request method type (GET, POST, PUT, DELETE).
In our example case, we want to send our model data in the POST body. On our controller, the
LongRunningDemoProcess
method will need to be decorated with the [HttpPost]
attribute, and accept the POST body payload as an argument.
Now let’s take a look at our
Home
controller.Basic Example – The Controller
For our purpose here, I have simply added a method named
LongRunningDemoProcess
to the stock ASP.NET MVC Home
Controller which is part of the default MVC 5 project template:A Basic Controller with Long-Running Process:
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
[HttpPost]
public JsonResult LongRunningDemoProcess(DemoViewModel model)
{
Thread.Sleep(1000);
return Json(model, "json");
}
public ActionResult About()
{
ViewBag.Message = "Your application description page.";
return View();
}
public ActionResult Contact()
{
ViewBag.Message = "Your contact page.";
return View();
}
}
In the above, we use
Thread.Sleep
to mimic a long-running process on the server. You will need to add a reference to the System.Threading
namespace in the using
statement imports at the top of your file.
As we can see,
LongRunningDemoProcess
is the target of for our HTTP Post request from the Index
view when form submission occurs. We want to use the Json data returned from the request to update our view, and let the user know their submit succeeded.
At the moment, though, things are not all they could be. We can load up our page, type some data into the form, and hit submit. What happens next, though, is that our page freezes up while the long-running process runs, and then our Json data is returned to a new tab in our browser (Chrome) or we are prompted to Save or Open (IE).
What we WANT to happen is to display a busy indicator, and then somehow indicate to the user that their submission was successful (or something!).
Get a Busy Indicator GIF
One of the more useful little sites I’ve found recently is AjaxLoad.Info, which presents a handy library of various customizable animated GIFs. You can specify some basic parameters (Size, Type, Foreground Color, etc.) and then download, ready to use.
Go get one, add it to your project in a location which makes sense (I am using ASP.NET MVC 5 project in VS 2013, so I placed mine at the root level of the Content folder).
Next, let’s modify our view, and add a div we can show and hide as needed, and which contains our gif:
The View, with Animated GIF and Placeholder for Submission Result
In the highlighted area below, we have added a div element to contain our Gif. While we’re at it, we also added another div, to hold the result when our long-running process returns:
Modified View with Animated Gif and Placeholder Div:
@model JqueryBusyExample.Models.DemoViewModel
@{
ViewBag.Title = "Home Page";
}
<h3>Enter Your Name and Submit:</h3>
@using (Html.BeginForm("LongRunningDemoProcess", "Home", FormMethod.Post,
new { encType = "multipart/form-data", id="myform", name = "myform" }))
{
<div class="form-group">
@Html.LabelFor(model => model.FirstName,
new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.FirstName)
@Html.ValidationMessageFor(model => model.FirstName)
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.LastName,
new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.LastName)
@Html.ValidationMessageFor(model => model.LastName)
</div>
</div>
<input type="submit" name="operation" id="process" value="process" />
}
// We want to show this while the server process is running:
<div id="divProcessing">
<p>Processing, please wait . . . <img src="../../Content/ajax-loader.gif"></p>
</div>
// We want to display the result from our submission in here:
<div id="divResult">
</div>
Now, in order to tie all this together, we need to add an Ajax request.
Adding the Ajax Request
The easiest way to achieve what we want is to use JavaScript on the client to show our animated gif, and then submit our data to the server. We also want to be able to respond when the Json is returned by the server by updating our page, without refreshing the whole thing.
For our example, I am going to add the JavaScript right on the view. This may or may not make sense in a production application, but we will do it here for simplicity.
I’ve added the JQuery code below our now-familiar view:
The View, with JQuery Added:
@model JqueryBusyExample.Models.DemoViewModel
@{
ViewBag.Title = "Home Page";
}
<h3>Enter Your Name and Submit:</h3>
@using (Html.BeginForm("LongRunningDemoProcess", "Home", FormMethod.Post,
new { encType = "multipart/form-data", id="myform", name = "myform" }))
{
<div class="form-group">
@Html.LabelFor(model => model.FirstName,
new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.FirstName)
@Html.ValidationMessageFor(model => model.FirstName)
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.LastName,
new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.LastName)
@Html.ValidationMessageFor(model => model.LastName)
</div>
</div>
<input type="submit" name="operation" id="process" value="process" />
}
// We want to show this while the server process is running:
<div id="divProcessing">
<p>Processing, please wait . . . <img src="../../Content/ajax-loader.gif"></p>
</div>
// We want to display the result from our submission in here:
<div id="divResult">
</div>
@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
<script type="text/javascript">
$(document).ready(function () {
// Hide the "busy" Gif at load:
$("#divProcessing").hide();
// Attach click handler to the submit button:
$('#process').click(function () {
$('#myform').submit();
});
// Handle the form submit event, and make the Ajax request:
$("#myform").on("submit", function (event) {
event.preventDefault();
// Show the "busy" Gif:
$("#divProcessing").show();
var url = $(this).attr("action");
var formData = $(this).serialize();
$.ajax({
url: url,
type: "POST",
data: formData,
dataType: "json",
success: function (resp) {
// Hide the "busy" gif:
$("#divProcessing").hide();
// Do something useful with the data:
$("<h3>" + resp.FirstName + " " + resp.LastName + "</h3>").appendTo("#divResult");
}
})
});
});
</script>
}
In the above, we start with the standard JQuery document.ready function, and hide the div containing our animated Gif.
We then attach the form submit event to the click event of the submit button we defined in our View (Isn’t it already attached, you ask? We’ll get to why we do this in a moment), and then we handle the form
submit
event.Handling the Form Submit Event with an Ajax Request
This is where things get interesting. There are a few things occurring inside this function, in a rather specific order. Let’s walk through it.
First, we want to prevent the default action using (wait for it . . .) the JQuery
preventDefault()
method when the form submit
event occurs, otherwise, form submission will proceed automatically, as before, and any code we place in our handler will not work properly.
Next, we show our animated Gif. Once shown, it will do its thing, giving the user the impression that something useful is happening.
Finally, we collect what we need from our form in order to submit our Ajax request. First, we grab the Url and stow it in a variable by accessing the form’s action attribute using JQuery. The
action
attribute essentially pulls a Url which matches the route we specified in the form declaration (remember? ActionMethod, ControllerName, HttpMethodType, etc?).
Next, we serialize the form data ( in this case, our model data) into another variable, again using JQuery.
Once we have collected these things, we can set up our Ajax request by making the property assignments shown. Note that we need to specify the data type as Json, so that when the request returns, JQuery will recognize it as valid Json. Then, we come to the all-important
success
property.
We have assigned a function here, which will execute when our long-running process returns a response. The
resp
argument will contain the Json returned from our controller method. In this very simple case, it is merely the data we already submitted. However, it could just as easily be the result of persisting some data in a database on the server. In any case, we know that when this function is called, our remote, long-running task has completed.
That being the case, the first thing we want to do is hide our animated Gif. Next, we push the returned data into the div we set up as a placeholder (after doing a little formatting, of course).
Fairly Simple, but Not Always Obvious
And there you have it. The example we have examined is pretty basic, but gives a good look at how to both display a busy indicator, and how to make Ajax requests from your ASP.NET MVC page.
There is a lot more to learn about Ajax, and it provides a foundation for much of the interactivity found in today’s modern websites. I welcome comments and constructive criticism in the comments section below (especially if I got something wrong here . . .)!
You can clone or download the example project from my Github Repo. Note that you will need to use Nuget Package Restore to pull in all the package dependencies. If you don’t know what that means, see Keep Nuget Packages Out of Source Control with Nuget Package Manager Restore.
kaynak: http://johnatten.com
Kaydol:
Kayıtlar (Atom)
evren pehlivan yazılım
evren pehlivan yazılım, evren pehlivan yazılım geliştirici
-
Letter Numerical Code Description Ç Ç Capital c-cedilla ç ç Lowercase c-cedilla Ğ Ğ Capital g-breve ğ ...
-
dataset adı dataSet1 olsun dataSet1.Tables["TabloAdı"].Rows[satırnumarası]["tablodakiSütunAdı"]; data table için de aynı...
-
@model WebTimeSheetManagement.Models.Registration @using CaptchaMvc.HtmlHelpers @{ ViewBag.Title = "CreateAdmin"; Layo...