Showing posts with label asp.net mvc. Show all posts
Showing posts with label asp.net mvc. Show all posts

mvc 5 web api routing

 
public class RouteConfig
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapMvcAttributeRoutes(); 
    }
}
//using


    public class ValuesController : ApiController
    {
        // GET api/values
        public IEnumerable Get()
        {
            return new string[] { "value1", "value2" };
        }

        // GET api/values/5
        public string Get(int id)
        {
            return "value";
        }

        [Route("customers/orders")]
        [HttpGet]
        public string FindOrdersByCustomer() 
        {
            return "Supervalue";
        }

        // POST api/values
        public void Post([FromBody]string value)
        {
        }

        // PUT api/values/5
        public void Put(int id, [FromBody]string value)
        {
        }

        // DELETE api/values/5
        public void Delete(int id)
        {
        }
    }


http://www.codeproject.com/Articles/774807/Attribute-Routing-in-ASP-NET-MVC-WebAPI
http://www.asp.net/web-api/overview/web-api-routing-and-actions/attribute-routing-in-web-api-2

Simple AngularJS Application ( ASP.NET MVC + VS 2013 )

1 Create ASP.NET MVC Application

2 Create WebAPI
    public class MoviesController : ApiController
    {
        public IEnumerable Get()
        {
            return new List {
                new Movie {Id=1, Title="Star Wars", Director="Lucas"},
                new Movie {Id=2, Title="King Kong", Director="Jackson"},
                new Movie {Id=3, Title="Memento", Director="Nolan"}
            };
        }

        public string Get(int id)
        {
            return "value";
        }

        public void Post([FromBody]string value)
        {
        }

        public void Put(int id, [FromBody]string value)
        {
        }


        public void Delete(int id)
        {
        }
    }

3 Change Index.cshtml
@{
    ViewBag.Title = "Home Page";
}

@section scripts {


    }

Title Director
{{movie.Title}} {{movie.Director}}

4 Check result



SignalR ASP NET Example

1 install nuget package


2 Add class Add | New Item | Visual C# | Web | SignalR | SignalR Hub Class (v2) 

3 Add Action to HomeController
4 Add view

5 Add Startup class
using Owin;
using Microsoft.Owin;
[assembly: OwinStartup(typeof(SignalRChat.Startup))]
namespace SignalRChat
{
    public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            // Any connection or hub wire up and configuration should go here
            app.MapSignalR();
        }
    }
}

6 Test




ASP NET Compression Caching

modify web.config
  
    
      
    
    
      
    
    
      
      
        
        
        
        
        
        
        
      
      
        
        
        
        
        
        
        
      
    
    
  
add attribute where it requers
        [OutputCache(Duration = int.MaxValue, VaryByParam = "none")]
        public ActionResult Index()
        {
            return View();
        }

ASP .NET MVC 5 Validation and Way to change standard validation message

my view
@model Riski.Models.Koef

@using (Html.BeginForm()) {
    

    @Html.AntiForgeryToken()
    

@Model.name


@Html.ValidationSummary(true, "", new { @class = "text-danger" })
@Html.LabelFor(model => model.koef1, htmlAttributes: new { @class = "control-label col-md-2" })
@Html.EditorFor(model => model.koef1, new { @class = "form-control" }) @Html.ValidationMessageFor(model => model.koef1, "", new { @class = "text-danger" })
@Html.HiddenFor(model => model.id) @Html.HiddenFor(model => model.name)
}
@Html.ActionLink("Вернуться к списку", "Index")
@section scripts{ @Scripts.Render("~/bundles/jqueryval") }
my controller
        [HttpPost]
        public ActionResult Edit(Koef koef)
        {
            if (ModelState.IsValid)
            {
                db.Configuration.ValidateOnSaveEnabled = false;

                db.Koefs.Attach(koef);
                var entry = db.Entry(koef);
                entry.Property(e => e.koef1).IsModified = true;

                db.SaveChanges();
                return RedirectToAction("Index");
            }
            return View(koef);
        }
this is a partial class wich helps us to validate our model. Acording to this approach we don't need to add Validation Attributies after every process of generation Entity classes
using System;
using System.ComponentModel.DataAnnotations;

namespace Riski.Models
{
    [MetadataType(typeof(KoefViewModel))]
    public partial class Koef
    {
    }

    public class KoefViewModel
    {
        [Required]
        [Display(Name = "Коэффициент")]
        [Range(0, 100, ErrorMessage = "Значение должно быть от 0 до 100.")]
        public Nullable koef1 { get; set; }

        [Required]
        public int id { get; set; }
    }
}
That's it. Now , as this is a russian web-site, we need to override some standard validation messages. It's simple solution and we should do only for steps

1 Add folder

2 Create resource file

3 Add new value (We can override 4 types of messages FieldMustBeDateFieldMustBeNumericPropertyValueInvalid andPropertyValueRequired)


4 And add one line to your Global.asax.cs
DefaultModelBinder.ResourceClassKey = "MyNewResource";

ASP NET MVC JQuery table with ajax refresh



       var oProtocolTable = $('#ProtocolTable').DataTable({
        "bPaginate": false,
        "ordering": false,
        "bFilter": false,
        "bInfo": false,
        "bProcessing": true,
        "bLengthChange": false,
        "ajax": "/Home/ProtocolAjaxHandler",
        "language": {
            "url": "Content/Russian.txt"
        },
        "fnServerParams": function (aoData) {
            aoData.push({ "name": "GroupID", "value": GroupID });
            aoData.push({ "name": "OrgInn", "value": orgINN });
            aoData.push({ "name": "check_id", "value": check_id });
        }
    });
 
    $('#OrganisationRisk tbody').on('click', 'tr', function () {
        check_id = oOrganisationRisk.cell(this, 0).data();
        oProtocolTable.ajax.reload();
    });

 /// <summary>
    /// Class that encapsulates most common parameters sent by DataTables plugin
    /// </summary>
    public class JQueryDataTableParamModel
    {
        /// <summary>
        /// Request sequence number sent by DataTable, same value must be returned in response
        /// </summary>       
        public string sEcho{ get; set; }
 
        /// <summary>
        /// Text used for filtering
        /// </summary>
        public string sSearch{ get; set; }
 
        /// <summary>
        /// Number of records that should be shown in table
        /// </summary>
        public int iDisplayLength{ get; set; }
 
        /// <summary>
        /// First record that should be shown(used for paging)
        /// </summary>
        public int iDisplayStart{ get; set; }
 
        /// <summary>
        /// Number of columns in table
        /// </summary>
        public int iColumns{ get; set; }
 
        /// <summary>
        /// Number of columns that are used in sorting
        /// </summary>
        public int iSortingCols{ get; set; }
 
        /// <summary>
        /// Comma separated list of column names
        /// </summary>
        public string sColumns{ get; set; }
 
    }


  public ActionResult ProtocolAjaxHandler(JQueryDataTableParamModel param, int? GroupID, string OrgInn, int? check_id)
        {
            var riski = RiskiRepository.Show_Protocol(OrgInn ?? "", GroupID ?? 0, check_id ?? 0);
            if (riski == null)
                return Json(new
                {
                    data = new List<string>()
                },
                JsonRequestBehavior.AllowGet);
            return Json(new
            {
                aaData = from emp in riski
                         select new[] { emp.description, emp.date_check.ToShortDateString() }
 
            },
            JsonRequestBehavior.AllowGet);
 
        }

ASP NET MVC JQUERY send ajax request and get results

var ooData = { GroupID: GroupID, OrgInn: orgINN, check_id: oOrganisationRisk.cell(this, 0).data() };
var jqxhr = $.post("/Home/ProtocolAjaxHandler", ooData, function (data) {
var ss = "";
$.each(data, function (i) {
  ss = ss + "<tr><td>" + this.description + "</td><td>" + this.date_check + "</td></tr>";
  });
$("#ProtocolTable").html(ss);


        [HttpPost]
        public ActionResult ProtocolAjaxHandler(ProtocolPost _param)
        {
            var riski = RiskiRepository.Show_Protocol(_param.OrgInn ?? "", _param.GroupID ?? 0, _param.check_id ?? 0);
            return Json(riski);
        }


        public class ProtocolPost
        {
            public string OrgInn {get;set;}
            public int? GroupID { get; set; }
            public int? check_id { get; set; }
        }




ASP NET JQuery Table with refreshing content

http://www.codeproject.com/Articles/177335/Refreshing-content-of-the-table-using-AJAX-in-ASP

https://evolpin.wordpress.com/2011/04/12/asp-net-mvc-partialview-with-ajax/
simple example of jquery ajax mvc

изучаем основы umbarco

Как добавить новый datatype в umbarco
1)руками
2)через wrapper
3)видео
4)динамик пропертис видео к этому

*как изменить default page в umbarco
просто поставить в дереве контента её на первое место

*как решить проблему по поводу того чтобы под разные девайсы и браузеры сжимался боди
вот что нашёл http://css-tricks.com/body-border/

*как добавить BingMap
да пожалйста,устанавливаем компонент и пишем
<form runat="server">
<umbraco:Macro bingMapNode="[#mainBingMap]" Alias="bingMapAdvanced" runat="server"></umbraco:Macro>
</form>

*как же это всё заделать под iphone
http://interpretor.ru/iphone_dev

*изменения размера шрифта от размера страницы
http://dimox.name/dynamic-font-size-on-jquery/

*что такое em pt %
http://www.askdev.ru/frontend/484/Размеры-в-em-ex-pt-px-в-чем-разница/

*какие же размеры экранов у девайсов
iphone - 320 х 480
ipad - 1024 x 768
у меня htc gratia 320x480 точно такое же как у iphone, так что можно тестировать

*как добавить bing map на свою страницу
http://msdn.microsoft.com/en-us/library/gg427610.aspx

*как вызвать один разор скрипт из другого
http://our.umbraco.org/forum/developers/razor/26993-Calling-Razor-from-Razor

*как узнать величину боди


*как чтобы div пальцем прокручивался на iphone
http://cubiq.org/iscroll

African Melody III (Melodia Africana III) by Ludovico Einaudi on Grooveshark

с# как прочитать web.config раздел appsettings / C# Read web.config section in appsettings

Всё очень просто оказывается
string s =System.Configuration.ConfigurationManager.AppSettings["smtpserver"];

А в файле web.config:
<appSettings>
  <add key="smtpserver" value="smtp.mail.ru"/>
</appSettings>