ラベル ASP.NET MVC の投稿を表示しています。 すべての投稿を表示
ラベル ASP.NET MVC の投稿を表示しています。 すべての投稿を表示

2022年9月6日火曜日

ASP.NET MVCでBootstrap 5.2を使用するとエラーになる

 ASP.NET MVCでBootstrap 5.2を使用するとエラーになる

実行すると bootstrap.jsを読み込んだ箇所でエラー

System.Web.MVC.dll が見つかりません

System.NullReferenceException
  HResult=0x80004003
  Message=Object reference not set to an instance of an object.
  Source=WebGrease
  StackTrace:
   at Microsoft.Ajax.Utilities.JSParser.ParseObjectLiteralProperty(Boolean isBindingPattern)
   at Microsoft.Ajax.Utilities.JSParser.ParseObjectLiteral(Boolean isBindingPattern)
   at Microsoft.Ajax.Utilities.JSParser.ParseLeftHandSideExpression(Boolean isMinus)
   at Microsoft.Ajax.Utilities.JSParser.ParseUnaryExpression(Boolean& isLeftHandSideExpr, Boolean isMinus)
   at Microsoft.Ajax.Utilities.JSParser.ParseExpressionList(JSToken terminator)
   at Microsoft.Ajax.Utilities.JSParser.ParseMemberExpression(AstNode expression, List`1 newContexts)
   at Microsoft.Ajax.Utilities.JSParser.ParseLeftHandSideExpression(Boolean isMinus)
   at Microsoft.Ajax.Utilities.JSParser.ParseUnaryExpression(Boolean& isLeftHandSideExpr, Boolean isMinus)
   at Microsoft.Ajax.Utilities.JSParser.ParseExpressionStatement(Boolean fSourceElement)
   at Microsoft.Ajax.Utilities.JSParser.ParseStatement(Boolean fSourceElement, Boolean skipImportantComment)
   at Microsoft.Ajax.Utilities.JSParser.ParseBlock()
   at Microsoft.Ajax.Utilities.JSParser.ParseArrowFunction(AstNode parameters)
   at Microsoft.Ajax.Utilities.JSParser.ParseLeftHandSideExpression(Boolean isMinus)
   at Microsoft.Ajax.Utilities.JSParser.ParseUnaryExpression(Boolean& isLeftHandSideExpr, Boolean isMinus)

 

解決方法

https://stackoverflow.com/questions/68009152/mvc-5-scripts-render-bundles-bootstrap-error-object-reference-not-set-to

 

         bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
                    "~/Scripts/jquery.validate*"));

        // Geliştirme yapmak ve öğrenme kaynağı olarak yararlanmak için Modernizr uygulamasının geliştirme sürümünü kullanın. Ardından
        // üretim için hazır. https://modernizr.com adresinde derleme aracını kullanarak yalnızca ihtiyacınız olan testleri seçin.
        bundles.Add(new ScriptBundle("~/bundles/modernizr").Include(
                    "~/Scripts/modernizr-*"));

        bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include(
                  "~/Scripts/bootstrap.js"));

        bundles.Add(new StyleBundle("~/Content/css").Include(
                  "~/Content/bootstrap.css",
                  "~/Content/site.css"));

        bundles.Add(new Bundle("~/bundles/bootstrap").Include(
                   "~/Scripts/bootstrap.js",
                   "~/Scripts/respond.js",
                   "~/Content/site.css"));
    }
}

 

 

Bundleを追加する


 

2021年8月31日火曜日

ASP.NET MVC で二重サブミットを防止したい

ASP.NET MVC で二重サブミットを防止したい

フォームなんかでボタンをうっかりダブルクリックしちゃって二重に投稿されてしまうのを防ぎたい。 クリックしたらボタンを無効にできればなお良し。

単純に JavaScript でボタンクリックされたら無効にするイベントハンドラ書けばいいと思ってたら、クライアントバリデーションに失敗したときボタンが押せなくなって困った。

なので今のところ

$(function () {
    $("form").on("submit", function (e) {
        var $form = $(this);
        // クライアントバリデーションに成功したら submit を無効にする
        if ($form.valid()) {
            $(this).find("[data-disable-with]").each(function () {
                var $button = $(this);
                var text = $button.attr("data-disable-with");
                $button.val(text);
                $button.prop("disabled", true);
            });
        }
    });
});

な感じでクライアントバリデーションに成功したらボタンを無効にするようにしている。Rails をマネして、data-disable-with 属性でボタンを無効にしたとき、ボタンのタイトルも変更できるようにもしてみた。

ビューでは

<input type="submit" value="ログイン" class="btn btn-lg btn-primary btn-block" data-disable-with="ログイン中..." />

という風に使っている。

 

元ネタ https://tnakamura.hatenablog.com/entry/2015/07/30/double-submit-protection

 

2021年7月7日水曜日

There is no ViewData item of type 'IEnumerable' that has the key 'Selected画像種別


 There is no ViewData item of type 'IEnumerable<SelectListItem>' that has the key 'Selected画像種別

 

ASP.NET MVC5で  以下のCSHTMLを作成

   @Html.DropDownListFor(m => m.Selected画像種別,
      (IEnumerable<SelectListItem>)Model.画像種別,
     new { @class = "btn dropdown-toggle dropdownlist" })


ViewModelは以下の通り

    public class ConfirmImageViewModel {
        public string StaffNo { get; set; }
        public string StaffName { get; set; }
        public string Selected画像種別 { get; set; }
        public string Selected年月 { get; set; }
        public string Selected承認状況 { get; set; }
        public List<SelectListItem> 画像種別s { get; set; }
        public List<SelectListItem> 年月s { get; set; }
        public List<SelectListItem> 承認状況s { get; set; }

 

Controllerは以下の通り

            var vm = new ConfirmImageViewModel();
            vm.画像種別s = new List<SelectListItem>();
            vm.年月s = new List<SelectListItem>();
            vm.承認状況s = new List<SelectListItem>();
            vm.datas = new List<ConfirmImageData>();

            vm.StaffNo = "";
            vm.StaffName = "";
            vm.Selected画像種別 = "";
            vm.Selected年月 = "";
            vm.Selected承認状況 = "";

            var m1s = db.Image管理.OrderBy(x => x.表示順);
            foreach (var m1 in m1s) {
                var item = new SelectListItem();
                item.Text = m1.Imageタイトル;
                item.Value = m1.ImageNo.ToString();
                vm.画像種別s.Add(item);
            }

 

DropDownListForのSelectListItemのList内にvm.Selected画像種別

の値が無いのが問題

 vm.Selected画像種別 = vm.画像種別s[0].Value;


vm.Selected画像種別の値をList内の値にすること


2021年3月13日土曜日

ASP.NET MVC RAZORでdesableにする方法

 ASP.NET MVC RAZORでdesableにする方法

 @Html.EditorFor(m => m.タイトル, new { htmlAttributes = new { id = "SPT_Title",
            @class = "SPT_Title", @disabled = "true" } }) 

@Html.TextAreaFor(m => m.問合せ内容,    // プロパティ
                10,                       // 行数
                600,                      // 桁数
                new { id = "SPT_Body", @class = "SPT_Body", @disabled = "true" }
            )

2020年11月13日金曜日

ASP.NET MVC 入力filter

 

半角カタカナ

[RegularExpression(@"[。-゚+]+", ErrorMessage = "半角カタカナのみ入力できます。")]
public string HalfKatakana { get; set; }

全角カタカナ

[RegularExpression(@"[ァ-ヶ]+", ErrorMessage = "全角カタカナのみ入力できます。")]
public string FullKatakana { get; set; }

2020年6月5日金曜日

telerik kendo ui timepicker のボタンを日本語化

htmlに以下のscriptを追加

    $(document).ready(function () {
        $('.k-time-accept').text('申請');
        $('.k-time-cancel').text('キャンセル');
    });

2020年5月1日金曜日

telerik asp.net mvc コンポーネントに Forがあった。

telerik asp.net mvc コンポーネントに Forがあった。

今まで DatePickerとかを  @(Html.Kendo().DatePicker  で記述していたが
データ渡しをしたい時、formCollectionから取得していた。

telerikのDocumentを参照したら  @(Html.Kendo().DatePickerFor
があるじゃないですか!

Documentを読まない自分を責めたい  ......Orz

2019年9月27日金曜日

ASP.NET MVC 物理パス取得

using System.Web.Hosting;

var physicalPath = HostingEnvironment.MapPath(絶対パス or 相対パス);

2019年3月9日土曜日

ASP.NET MVC:全ての例外をログに出力する

ASP.NET MVC:全ての例外をログに出力する

エラー発生時エラー情報を画面に表示していたが
エンドユーザーからPCが壊れたと勘違いするので表示を辞めた。
今まではglobal.asaxのクラスApplicarion_Error内に
エラー内容をログとして出力していたがcontoller内のエラーはApplication_Errorを

通過しないことが分かった。

方法としてfilterにhandleerrorattributeと同様にログ出力クラスを定義する。
上記クラスでログ出力を行う。

https://paulthecyclist.com/2013/05/17/log-all-mvc-errors/

上記リンク先を参照

自分はlog4net ではなくNLogを使用しました。


App_Start/FilterConfig.cs

 public class FilterConfig {
        private static ILogger logger = LogManager.GetLogger("logfile");

        public static void RegisterGlobalFilters(GlobalFilterCollection filters, ILogger logger) {
            filters.Add(new HandleErrorAttribute());
            filters.Add(new ExceptionLoggingFilter(logger));  // add
        }
    }

ExceptionLoggingFilter.cs

    public class ExceptionLoggingFilter : IExceptionFilter {

        private static ILogger _logger = LogManager.GetLogger("logfile");

        public ExceptionLoggingFilter(ILogger logger) {
            _logger = logger;
        }

        public virtual void OnException(ExceptionContext filterContext) {
            _logger.Error("contller : " + filterContext.Controller);
            _logger.Error(filterContext.Exception);
        }

        public interface IExceptionFilter {
            void OnException(ExceptionContext filterContext);
        }
    }

Global.asax.cs

 protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);

            ILogger logger = LogManager.GetLogger("logfile");

            AreaRegistration.RegisterAllAreas();
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters, logger);
           
        }

2019年2月26日火曜日

asp.net mvcでgoogle web fontを使いたい

asp.net mvcでgoogle web fontを使う方法

asp.net mvcのprojectにwebfontsフォルダを作成後
google web fontをそのフォルダに展開する。

プログラムではcssに以下のように指定する。

@font-face {
    font-family: 'Noto Sans JP';
    font-style: normal;
    font-weight: 100;
    src: url('webfonts/NotoSans-Thin.ttf') format('truetype');
}

@font-face {
    font-family: 'Noto Sans JP';
    font-style: normal;
    font-weight: 300;
    src: url('webfonts/NotoSans-Thin.ttf') format('truetype');
}

@font-face {
    font-family: 'Noto Sans JP';
    font-style: normal;
    font-weight: 400;
    src: url('webfonts/NotoSans-Regular.ttf') format('truetype');
}

@font-face {
    font-family: 'Noto Sans JP';
    font-style: normal;
    font-weight: 500;
    src: url('webfonts/NotoSans-Medium.ttf') format('truetype');
}

@font-face {
    font-family: 'Noto Sans JP';
    font-style: normal;
    font-weight: 700;
    src: url('webfonts/NotoSans-Bold.ttf') format('truetype');
}

@font-face {
    font-family: 'Noto Sans JP';
    font-style: normal;
    font-weight: 900;
    src: url('webfonts/NotoSans-Black.ttf') format('truetype');
}


src: urlで指定するfontを指定することでfontが使えた

※macのヒラノギfontってかっこいいよなぁ~

2019年1月21日月曜日

telerik ASP.NET MVC GridのRead ActionにrouteValueを設定する

.DataSource(dataSource => dataSource
                    .Ajax()
                    .PageSize(20)
                    .Read(read => read.Action("Apply_Read", "APP", new { iSelect = ViewBag.SelectSearch }))
                    .Model(model => model.Id(p => p.ID))
                )

read.Action("アクション名","コントローラー名", new { パラメータ名 = 値})

※パラメータ名をidにするとうまく動かなかった。

2019年1月8日火曜日

ASP.NET MVCのWiki ライセンスはMS-PL

ASP.NET MVCのWiki、ライセンスはMS-PL

OSSが有ると大変助かります。

ソースはgithub
https://github.com/roadkillwiki/roadkill

デモサイトは
http://demo.roadkillwiki.net/

simple で気に入りました。

v2は MVC5 RAZORで構築
v3は .NET Coreで構築中?

.NET Coreで構築出来ると、RuntimeがLinuxになって
社内的に1サービス = 1Linuxとか楽出来そうです。


2018年12月25日火曜日

ASP.NET MVCのKANBAN Library


ASP.NET MVCのKANBAN Libraryを探していたからNugetにあった。

元はgithubに
https://github.com/DlhSoftTeam/Angular-Kanban

個人で管理するならこれくらいで十分
todo見たいに管理出来るから簡単なイメージが良いです。

2018年12月14日金曜日

Telerik ASP.NET MVC Schedulerの日付設定

Kendo().Schedulerで当日日付の指定

@(Html.Kendo().Scheduler<AskaGroup.Models.EventViewModel>()
    .Name("scheduler")
    .Date(new DateTime(DateTime.Today.Year, DateTime.Today.Month, DateTime.Today.Day))
    .StartTime(new DateTime(DateTime.Today.Year, DateTime.Today.Month, DateTime.Today.Day, 9, 00, 00))

    .Height(600)
    .Views(views => {
        views.DayView();
        views.WeekView(weekView => weekView.Selected(true));
        views.MonthView();
        views.AgendaView();
    })
    .Timezone("Etc/UTC")
    .DataSource(d => d
        .Model(m => {
            m.Id(f => f.EventID);
            m.Field(f => f.OwnerID).DefaultValue('1');
            //Set the recurrence ID field from the model:
            m.RecurrenceId(f => f.RecurrenceID);
        })
        .Read("Event_Read", "SDL")
        .Create("Event_Create", "SDL")
        .Destroy("Event_Destroy", "SDL")
        .Update("Event_Update", "SDL")
    )
)

2018年4月7日土曜日

ASP.NET MVC クッキーの削除

// Cookie の削除
    protected void Button2_Click(object sender, EventArgs e)
    {
        // Cookie 削除例1
        Response.Cookies["userId"].Value = "UID0001";                  // Cookie の値
        Response.Cookies["userId"].Expires = DateTime.Now.AddDays(-3); // Cookie の有効期間(3日前)
 
        // Cookie 削除例2
        HttpCookie cookie = new HttpCookie("userName");
 
        cookie.Value = "<まさお>";               // Cookie の値
        cookie.Expires = DateTime.Now.AddDays(-3); // Cookie の有効期間(3日前)
        Response.Cookies.Add(cookie);
    }

2018年1月30日火曜日

elFinder.NET

elFinderがPHPで作成されている。
これを.NETで焼き直ししたOSSがGitHubにあった。

ソースをImportさせてもらう。


2018年1月15日月曜日

telerik MVC Gridのページング方法は、戻り値を
ToDataSourceResult(request) でラップすることで実装する。


using Kendo.Mvc.Extensions;
using Kendo.Mvc.UI;


        //申請一覧取得
        public ActionResult Approval_Read([DataSourceRequest] DataSourceRequest request) {

            return Json(Get申請一覧().ToDataSourceResult(request));
        }

        private IEnumerable<ApprovalViewModel> Get申請一覧() {
            using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["db"].ToString())) {

                string sql = "select * from v申請H where 申請タイプ in (1, 2, 3, 4) and 申請者社員ID = @申請者社員ID order by ID desc";
                conn.Open();
                var recs = conn.Query<v申請H>(sql,
                    new {
                        申請者社員ID = Session["UserID"].ToString()
                    });

                List<ApprovalViewModel> 申請ViewModels = new List<ApprovalViewModel>();

                foreach (var rec in recs) {
                    ApprovalViewModel 申請ViewModel = new ApprovalViewModel() {
                        申請者社員姓 = rec.申請者社員姓,
                        状態 = rec.申請状態名,
                        申請書名 = rec.申請タイプ名称,
                        申請No = rec.ID,
                        決済No = rec.決済No,
                        件名 = rec.件名,
                        発注先 = rec.発注先名,
                        金額 = rec.金額
                    };
                    申請ViewModels.Add(申請ViewModel);
                }

                return 申請ViewModels;
            }
        }

2018年1月10日水曜日

Telerik MVC upload Select filesの文字を変更

        @(Html.Kendo().Upload()
            .Name("files")
            .Messages(m => m.Select("添付ファイル追加...."))
        )

元ネタ