顯示具有 ASP.NET MVC 標籤的文章。 顯示所有文章
顯示具有 ASP.NET MVC 標籤的文章。 顯示所有文章

2016年12月28日 星期三

[ASP.NET MVC] 登入後,自動導向使用者原本Request的Url

練習筆記...


User 驗証未通過,登入後,自動導向User原本Request的Url,三種作法:
1. 使用FormsAuthentication
2. 使用ViewBag
3. 使用讀寫屬性


1. 使用FormsAuthentication
FormsAuthentication.RedirectFromLoginPage(username, false);

2.使用ViewBag

@using (Html.BeginForm("index", "login", new { ReturnUrl = ViewBag.ReturnUrl }, FormMethod.Post, new { autocomplete = "off" }))
{
@Html.TextBoxFor(m => m.Account)
@Html.TextBoxFor(m => m.Password)

<button class="btn btn-lg btn-primary btn-block" type="submit">登入</button>
}

[AllowAnonymous, HttpGet]
public ActionResult Index(string returnUrl)
{
ViewBag.ReturnUrl = returnUrl;
return View();
}


3.使用讀寫屬性

public string ReturnUrl { get; set; }


@using (Html.BeginForm("index", "login", new { ReturnUrl = Model.ReturnUrl }, FormMethod.Post, new { autocomplete = "off" }))
{
@Html.TextBoxFor(m => m.Account)
@Html.TextBoxFor(m => m.Password)

<button class="btn btn-lg btn-primary btn-block" type="submit">登入</button>

}


[HttpGet]
public ActionResult Index(string returnUrl)
{
LoginViewModel model = new LoginViewModel() { ReturnUrl = returnUrl };
return View(model);
}


HttpPost ActionResult


[HttpPost]
public ActionResult Index(LoginViewModel data, string returnUrl)
{
//Todo something

if (string.IsNullOrWhiteSpace(returnUrl))
//RedirectToAction default url or other.
else
return Redirect(returnUrl);

return View();
}


Ref:
1. ASP.net MVC整合FormsAuthentication表單驗證登入
https://dotblogs.com.tw/shadow/archive/2014/03/01/144191.aspx
2. Asp.net MVC 實作登入驗證(1)
http://marco.easyusing.com/2013/10/mvc-1-mvc-mvc-mvc5-build-4.html

[ASP.NET MVC] Cookie與FormsAuthentication表單驗證自動登入

練習筆記...


[寫入Cookie]

寫法一:
HttpCookie cookie = new HttpCookie("UserData");
cookie.Value = JsonConvert.SerializeObject(userData);
cookie.Expires = DateTime.Now.AddDays(1d);

Response.Cookies.Add(cookie);



寫法二:
HttpCookie cookie = new HttpCookie("UserData")
{
       Value = JsonConvert.SerializeObject(userData),
       Expires = DateTime.Now.AddDays(1d),
};
Response.Cookies.Add(cookie); 


[取得Cookie]
HttpCookie authCookie = Request.Cookies["UserData”];


[FormsAuthentication寫入Cookie] 

FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
      version: 1,
      name: data.Account,
      issueDate: DateTime.Now,
      expiration: DateTime.Now.AddDays(1),
      isPersistent: false,
      userData: JsonConvert.SerializeObject(userData),
      cookiePath: FormsAuthentication.FormsCookiePath);

var encryptTicket = FormsAuthentication.Encrypt(ticket);
HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptTicket);
cookie.Expires = ticket.Expiration;
cookie.HttpOnly = true;
Response.Cookies.Add(cookie);

※ Cookie name 一定要用FormsAuthentication的CookieName => FormsAuthentication.FormsCookieName


[取得FormsAuthentication寫入的Cookie]

HttpCookie cookie = GetCookie(FormsAuthentication.FormsCookieName);



Ref:
1. 寫入 Authentication Cookie 的 FormsAuthenticationTicket.UserData
2. session與cookies與FormsAuthentication自動登入機制
3. ASP.net MVC整合FormsAuthentication表單驗證登入

2016年12月26日 星期一

[ASP.NET MVC] 空白MVC專案實作BundleConfig

練習筆記...


[實作步驟]

1. 在「App_Start」資料夾自行建立「BundleConfig.cs」

2. 在Global.asax.cs 註冊Bundles


BundleConfig.RegisterBundles(BundleTable.Bundles);


3. Web.Config新增Optimization 命名空間

<namespaces>
    <add namespace="System.Web.Optimization"/>   
</namespaces>


[使用方法]

@Styles.Render("~/Content/css”)
@Scripts.Render("~/Scripts/bootstrap”)
@Scripts.Render("~/Scripts/jquery”)



Ref:
http://demo.tc/post/779
http://aspnetmars.blogspot.tw/2016/05/aspnet-mvc-bundleconfig.html

2016年12月25日 星期日

[MVC] Server Error "owin:AutomaticAppStartup"

遇到就筆記一下…


[問題描述]

在空白MVC專案,從NuGet Package 安裝Owin套件後執行,發生錯誤訊息「To disable OWIN startup discovery, add the appSetting owin:AutomaticAppStartup with a value of "false" in your web.config…」


[錯誤訊息]

'/' 應用程式中發生伺服器錯誤。


The following errors occurred while attempting to load the app.
- No assembly found containing an OwinStartupAttribute.
- No assembly found containing a Startup or [AssemblyName].Startup class.
To disable OWIN startup discovery, add the appSetting owin:AutomaticAppStartup with a value of "false" in your web.config.
To specify the OWIN startup Assembly, Class, or Method, add the appSetting owin:AppStartup with the fully qualified startup class or configuration method name in your web.config.



[解決方案]

在Web.config加入
<add key="owin:AutomaticAppStartup" value="false" /> 



Ref: 
OwinStartupAttribute required in web.config to correct Server Error

2016年12月4日 星期日

[MVC][Razor][C#] How to populate dropdown list with numbers


A note to myself


@Html.DropDownListFor(m=>m.Name, Enumerable.Range(1, 10).Select(i => new SelectListItem { Text = i.ToString(), Value = i.ToString() }))



@Html.DropDownListFor(m => m.NumberOfTickets, Enumerable.Range(1, 10).Select(i => new SelectListItem { Text = i.ToString(), Value = i.ToString() }))



Ref:
1. How to populate dropdown list with numbers
http://stackoverflow.com/questions/29659911/asp-net-mvc-how-to-populate-dropdown-list-with-numbers
2. SelectList for years
http://stackoverflow.com/questions/13959098/selectlist-for-years

2016年10月23日 星期日

[MVC] [IIS] IIS部署asp.net mvc網站 HTTP錯誤 403.14-Forbidden

遇到就筆記一下…


【狀況描述】
    IIS 部署asp.net mvc網站HTTP錯誤:「HTTP錯誤403.14-Forbidden Web 伺服器被配置為不列出此目錄的內容及Login on failed for "IIS APPPOOL\ASP.NET v4.0"」

【主要原因】
    IIS是在安裝完.net framework 之後才安裝的。

【解決方案】
    至 cmd 控制台,將ASP.NET重新註冊到IIS即可解決此錯誤。

  64bit: 
    C:/Windows/Microsoft.NET/Framework64/v4.0.30319/aspnet_regiis.exe -i 

  32bit:
    C:/Windows/Microsoft.NET/Framework/v4.0.30319/aspnet_regiis.exe -i


reference: https://read01.com/5Q0DQ4.html

2016年10月10日 星期一

[MVC][C#] json parse data to ajax

Just a note to myself.


importment:

Return Json data to Ajax
Json(data, JsonRequestBehavior.AllowGet);

Jquery update Json result data

 $("#email").text(result.email);

Debug:

 console.log(result.status);



Controller
   [HttpPost]
        public ActionResult editemail(string email)
        {
            bool result = false;

            if (!string.IsNullOrWhiteSpace(email) && (EditEmail(hid, email)))
                result = true;
            var data = new { status = result, email = email };

            return Json(data, JsonRequestBehavior.AllowGet);
        }

View

<label id="lb_email">@(Model.UserData.email)</label>  ] 


Ajax
 $.ajax({
                url: '/rivatest/editemail/',
                data: { email: email },
                type: 'POST',
                datatype:'json',
                cache: false
            }).success(function (result) {
                //console.log(result);
               
                if (result.status==true) {
                    $("#email").text(result.email);
                }
                else { 
                    alert('Edit Email failed。');
                }
                
                console.log(result.status);
                console.log(result.email);
           
            }).error(function (result) {
                alert(result);

            });

2016年9月21日 星期三

[ASP.NET MVC] 一個View 顯示不同的 Domain Model

Just a note to myself...


如果有個需求,希望一個 View 能顯示不同的 Domain Model 類別的資料,該怎麼做呢…
那就自訂一個 ViewModel 吧! 


Steps:
1. Model: 自訂 IndexViewModel.cs
2. Controller: 在 Controller 把想要呈現資料的物件 (IndexViewModel) 準備好,並傳給View。
3. View: 在View設定@model 的類別為它 (IndexViewModel)

View

@model ModelExample.Models.IndexViewModel

@{ Layout = null; }

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
</head>
<body>
    <div style="float:left;">
        <table border="1">
            <tr>
                <th>
                    @Html.LabelFor(m =>m.Students[0].Identity)
                </th>
                <th>
                    @Html.LabelFor(m => m.Students[0].FullName)
                </th>
            </tr>
            @foreach (var student in this.Model.Students)
            {
                <tr>
                    <td>@student.Identity</td>
                    <td>@student.FullName</td>
                </tr>
            }
        </table>
    </div>

    <div style="float:left">
        <table border="1">
            <tr>
                <th>
                    @Html.LabelFor(m => m.Teachers[0].Identity)
                </th>
                <th>
                    @Html.LabelFor(m => m.Teachers[0].FullName)
                </th>
            </tr>
            @foreach (var teacher in this.Model.Teachers)
            {
                <tr>
                    <td>@teacher.Identity</td>
                    <td>@teacher.FullName</td>
                </tr>
            }
        </table>
    </div>
</body>
</html>


Controller
namespace ModelExample.Controllers
{
    public class HomeController : Controller
    {
        // GET: Home
        public ActionResult Index()
        {
            List<Student> students = new List<Student>();
            for (int i = 0; i < 25; i++)
            {
                Student student = new Student();
                student.Identity = i;
                student.FullName = string.Format("Student-{0}",i.ToString().PadLeft(2,'0'));
                students.Add(student);
            }

            List<Teacher> teachers = new List<Teacher>();
            for (int i = 0; i < 25; i++)
            {
                Teacher teacher = new Teacher();
                teacher.Identity = i;
                teacher.FullName = string.Format("Teacher-{0}", i.ToString().PadLeft(2, '0'));
                teachers.Add(teacher);
            }

            IndexViewModel vm = new IndexViewModel();
            vm.Students = students;
            vm.Teachers = teachers;

            return View(vm);
        }
    }



Model
IndexViewModel

namespace ModelExample.Models
{
    public class IndexViewModel
    {
        public List<Student> Students { get; set; }
        public List<Teacher> Teachers { get; set; }
    }
}


Student

namespace ModelExample.Models
{
    public class Student
    {
        public int Identity { get; set; }
        public string FullName { get; set; }
    }
}


Teacher

namespace ModelExample.Models
{
    public class Teacher
    {
        public int Identity { get; set; }
        public string FullName { get; set; }
    }
}




https://www.youtube.com/watch?v=4os5xejpJv0

[ASP.NET MVC] @Html.Action In Layout Page

遇到就筆記一下…


In the _ViewStart
Set Layout = null or mark it.
@{
    Layout = null;  //Layout = "~/Views/Shared/_Layout.cshtml";
 }



In the _Layout.cshtml 

Use @Html.Action(actionName, controllerName)
 <div id="header">
        @Html.Action("HeadMenu", "Home")
 </div>


In the Controller 
  
  public class HomeController : Controller
    {
        public ActionResult HeadMen()
        {
            //TODO something...
            return View();
        }
   }




http://weblogs.asp.net/scottgu/asp-net-mvc-3-layouts

2016年9月19日 星期一

[ASP.NET MVC] Html Helper Extensions


Just a note to myself...

Step 1: Custom Html Helper Extensions


namespace MvcExample.Extensions
{
    public static class WaspecExtentions
    {
        public static MvcHtmlString H2(this HtmlHelper htmlHelper, string content)
        {
            TagBuilder tagBuilder = new TagBuilder("h2");
            tagBuilder.InnerHtml = content;
            MvcHtmlString result = MvcHtmlString.Create(tagBuilder.ToString(TagRenderMode.Normal));  //<h2></h2>
            return result;
        }

        public static MvcHtmlString Hehehe(this HtmlHelper htmlHelper, string name, object value)
        {
            TagBuilder tagBuilder = new TagBuilder("input");
            tagBuilder.MergeAttribute("id", name);
            tagBuilder.MergeAttribute("name", name);
            tagBuilder.MergeAttribute("type", "text");
            tagBuilder.MergeAttribute("value", value.ToString());
            tagBuilder.MergeAttribute("class", "blueTextBox");
            MvcHtmlString result = MvcHtmlString.Create(tagBuilder.ToString(TagRenderMode.SelfClosing));  //<input .../>
            return result;
        }
    }
}



Step 2: Use them


    @Html.H2("How are you!")
    @Html.Hehehe("textBox2", "Hello!")




※ Other note for me:

    @Html.TextBox("textBox1", DateTime.Now, new { Blahblah="bbb", @class="blueTextBox"})<br/>
    <input type="text" id="textBox3" name="textBox3" value="@DateTime.Now" class="blueTextBox" />
    @Html.CheckBox("checkBox1",true) Are you ASP.NET MVC student?


2016年8月21日 星期日

[ASP.NET MVC] Razor @helper語法

Reference: http://blog.sanc.idv.tw/2011/08/aspnet-mvc-razorhelper.html

Just a note to myself...

test.cshtml


<!--寫法1-->
<div>
    @if (int.Parse(ViewData["score"].ToString()) >= 60)
    {
        <span>合格!</span>
    }
    else
    {
        <span>不合格!</span>
    }
</div>

<!--寫法2: 寫成 helper-->

@helper DisplayScore(int score)
{
    if (score >= 60)
    {
        <span>合格!</span>
    }
    else
    {
        <span>不合格!</span>
    }
} 
<div>
    @DisplayScore(int.Parse(ViewData["score"].ToString()))
</div>


<!--寫法3: 不同page都要使用它時, 把 helper 寫在App_Code裡-->
@RivaFuns.DisplayScore(int.Parse(ViewData["score"].ToString()))



App_Code > RivaFuns.cshtml



@helper DisplayScore(int score)
{
    if (score >= 60)
    {
        <span>合格!</span>
    }
    else
    {
        <span>不合格!</span>
    }
}