ProgramingTip

Razor 엔진을 사용하여 MVC 5 프로젝트에 Date Picker Bootstrap 3을 추가하는 방법은 무엇입니까?

bestdevel 2020. 10. 23. 08:10
반응형

Razor 엔진을 사용하여 MVC 5 프로젝트에 Date Picker Bootstrap 3을 추가하는 방법은 무엇입니까?


Razor 엔진을 사용하여 MVC 5 프로젝트에 Date Picker Bootstrap 3 을 설치하는 방법이 필요합니다 . 여기에서 에서이 링크를 찾았지만 VS2013에서 작동하도록 만들 수 없습니다.

위의 이후 링크의 예제에서 복사하여 이미 다음을 수행했습니다.

            bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include(
                  "~/Scripts/bootstrap.js",
                  "~/Scripts/bootstrap-datepicker.js",    // ** NEW for Bootstrap Datepicker
                  "~/Scripts/respond.js"));

        bundles.Add(new StyleBundle("~/Content/css").Include(
                  "~/Content/bootstrap.css",
                  "~/Content/bootstrap-datepicker.css",  // ** NEW for Bootstrap Datepicker
                  "~/Content/site.css"));

그런 다음 다음과 같이 색인보기에 펼쳐 놓았습니다.

@section Scripts {
@Scripts.Render("~/bundles/jqueryval")

<script type="text/javascript">
    $('.datepicker').datepicker(); //Initialise any date pickers
</script>
}

자, 여기서 날짜 선택기를 호출하는 방법은 무엇입니까?

   <div class="form-group input-group-sm">
    @Html.LabelFor(model => model.DropOffDate)
    @Html.TextBoxFor(model => model.DropOffDate, new { @class = "form-control", placeholder = "Enter Drop-off date here..." })
    @Html.ValidationMessageFor(model => model.DropOffDate)
</div>

이 답변은 별도의 포함 인 jQuery UI Datepicker를 사용합니다 . jQuery UI를 포함하지 않고 수행하는 다른 방법이 있습니다.

다음과 먼저 datepicker같이 텍스트 상자에 클래스를 추가하기 만하면 됩니다 form-control.

<div class="form-group input-group-sm">
    @Html.LabelFor(model => model.DropOffDate)
    @Html.TextBoxFor(model => model.DropOffDate, new { @class = "form-control datepicker", placeholder = "Enter Drop-off date here..." })
    @Html.ValidationMessageFor(model => model.DropOffDate)
</div>

그런 다음 텍스트 상자가 제시된 후 자바 펼쳐가 트리거 될 jQuery 준비 함수에 datepicker를 호출합니다.

<script type="text/javascript">
    $(function () { // will trigger when the document is ready
       $('.datepicker').datepicker(); //Initialise any date pickers
    });
</script>

이 답변 은 HTML 요소에 type=date속성적용하고 input브라우저에 의존하여 날짜 선택기를 제공합니다. 2017 년에도 모든 브라우저가 자체적으로 제공하는 것이 좋습니다.

뷰 모델의 속성에 속성을 추가하기 만하면됩니다. 변수 예 Ldate:

[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
Public DateTime Ldate {get;set;}

MVC 5 및 Visual Studio 2013을 사용하고 가정합니다.


나는 그것이 내 같은 문제에 직면하게 될 것입니다.

부트는 부트 클래식에 기본이 아닌 Bootstrap DatePicker Plugin을 사용합니다 .

NuGet을 통해 Bootstrap DatePicker를 설치해야합니다.

작은 JavaScript 조각을 만들고 이름을 DatePickerReady.js로 지정하고 스크립트 디렉토리에 저장합니다. 이렇게하면 거의 없지만 HTML5가 아닌 브라우저 작동합니다.

if (!Modernizr.inputtypes.date) {
    $(function () {

       $(".datecontrol").datepicker();

    });
}

보다 설정

bundles.Add(New ScriptBundle("~/bundles/bootstrap").Include(
              "~/Scripts/bootstrap.js",
              "~/Scripts/bootstrap-datepicker.js",
              "~/Scripts/DatePickerReady.js",
              "~/Scripts/respond.js"))

bundles.Add(New StyleBundle("~/Content/css").Include(
              "~/Content/bootstrap.css",
              "~/Content/bootstrap-datepicker3.css",
              "~/Content/site.css"))

이제 EditorFor를 사용할 때 MVC가 사용할 대상을 방송하도록 데이터 유형을 설정합니다.

<Required>
<DataType(DataType.Date)>
Public Property DOB As DateTime? = Nothing

보기 코드는

@Html.EditorFor(Function(model) model.DOB, New With {.htmlAttributes = New With {.class = "form-control datecontrol", .PlaceHolder = "Enter Date of Birth"}})

그리고 짜잔

여기에 이미지 설명 입력


모델의 datetime 속성이 두 줄만 추가합니다.

[DataType(DataType.Date)] 
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]

결과는 다음과 가변적입니다.MVC 애플리케이션의 날짜 선택기


Enzero 의 답변에 따라 간결한 업데이트를 제공합니다.

  • Bootstrap.Datepicker 패키지를 설치합니다 .

    PM> install-package Bootstrap.Datepicker
    ...
    Successfully installed 'Bootstrap.Datepicker 1.7.1' to ...
    
  • 에서 AppStart / BundleConfig.cs , 확장에 관련과 스타일을 추가 할 수 있습니다.

    bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include(
          //...,
          "~/Scripts/bootstrap-datepicker.js",
          "~/Scripts/locales/bootstrap-datepicker.YOUR-LOCALE-CODE-HERE.min.js"));
    
    bundles.Add(new StyleBundle("~/Content/css").Include(
          ...,
          "~/Content/bootstrap-datepicker3.css"));
    
  • 관련보기의 펼쳐보기 섹션에서 datepicker를 활성화하고 사용자를 지정합니다.

    @section scripts{
        <script type="text/javascript">
            //...
            $('.datepicker').datepicker({
                format: 'dd/mm/yyyy', //choose the date format you prefer
                language: "YOUR-LOCALE-CODE-HERE",
                orientation: 'left bottom'
            });
        </script>
    
  • 결국 관련 컨트롤에 datepicker 클래스를 추가합니다 . 예를 들어, TextBox 및 "31/12/2018"과 같은 날짜 형식의 경우 다음과 같습니다.

    @Html.TextBox("YOUR-STRING-FOR-THE-DATE", "{0:dd/MM/yyyy}", new { @class = "datepicker" })
    

[DataType(DataType.Date)]
public DateTime BirthDate { get; set; }

이렇게 모델을 장식하십시오. 부트 스트랩 날짜 시간 선택기를 사용할 수 있습니다. https://github.com/Eonasdan/bootstrap-datetimepicker/

부트 스트랩 CSS 및 JS에 대한 번들이 이미 있다고 가정합니다.

날짜 선택기 번들 항목

 bundles.Add(new ScriptBundle("~/bundles/datePicker").Include(
           "~/Scripts/moment.min.js",
           "~/Scripts/bootstrap-datetimepicker.min.js"));

        bundles.Add(new StyleBundle("~/Content/datepicker").Include(
                 "~/Content/bootstrap-datetimepicker.min.css"));

레이아웃보기에서 번들 렌더링

@Styles.Render("~/Content/datepicker")
@Scripts.Render("~/bundles/datePicker")

보기에 HTML

<div class="form-group">
        @Html.LabelFor(model => model.BirthDate, htmlAttributes: new { @class = "lead col-md-2" })
        <div class="col-md-10">
            @Html.TextBoxFor(model => model.BirthDate, new { @class = "datetimepicker form-control" })
            @Html.ValidationMessageFor(model => model.BirthDate, "", new { @class = "text-danger" })
        </div>
</div>

보기 끝에 이것을 추가하십시오.

<script>
    $(document).ready(function () {
        $('.datetimepicker').datetimepicker({
            format: 'lll'
        });
    });
</script>

1. 처음에
jquery.js 를 참조해야합니다. 2. 레이아웃을 확인하고 "~ / bundles / bootstrap"을 호출했는지 확인합니다. 3. 레이아웃을 확인하고
렌더 섹션을 참조하십시오. 펼쳐지는 위치, "~ / bundles / bootstrap"뒤에 있어야합니다.
4. 텍스트 상자에 클래스 "datepicker"추가
5. $ ( '. datepicker')를 입력합니다. 날짜 선택기 (); $ (함수 () {...});


Checkout Shield UI의 MVC 용 날짜 선택기 . 다음과 같은 몇 줄로 통합 할 수있는 강력한 구성 요소입니다.

@(Html.ShieldDatePicker()
    .Name("datepicker"))

단순한 :

[DataType(DataType.Date)]
Public DateTime Ldate {get;set;}

참고 URL : https://stackoverflow.com/questions/21104633/how-to-add-date-picker-bootstrap-3-on-mvc-5-project-using-the-razor-engine

반응형