2012-05-08 12 views
0

実際にどのようにフレーズするのかわからない。MVC、日付のプロパティにテキスト値を入力

ほとんどの私の画面(この場合、関連する情報が不明)で、jqgridを使用しています。 Iv'eは、追加/編集モーダルで2つのdatetimeピッカーを取得しています。私はthis Date Timeピッカーコンポーネントを使用していましたが、人が頻繁に入力する必要がある場合は、時間をキャプチャするためにスライダを使用するファンではありません。 P、

(私の他のオプションを試してみて、私自身のコンポーネントを書くことだったが、私はそれを今のスキップをあげる)、私のエンドユーザーの祈りに答えるように見えた:

に沿って超発光がwill_pickdateコンポーネントが来ました

私が試して保存するときに問題が発生します。 will_pickdateコンポーネントは、テキストとして、またはTryUpdateModelメソッドを呼び出すときに正しくマッピングされていない、日付の時間値を送信しているようです。

クライアント側のコード

 function CreateDateTimePicker(elem, ShowOn, OnClose) { 

     setTimeout(function() { 
    //code that works 
      $(elem).datetimepicker({ 
       dateFormat: 'yy/mm/dd', 
       timeFormat: 'hh:mm', 
       showOn: ShowOn, 
       buttonImageOnly: true, 
       buttonImage: "/Images/date_time.jpg", 
       changeYear: true, 
       changeMonth: true, 
       showButtonPanel: true, 
       showWeek: true, 
       onClose: function (dateText, inst) { 
        if (OnClose != null) 
         OnClose(dateText, inst); 

        $(this).focus(); 
       } 
      }).attr('size', '16').next('img.ui-datepicker-trigger') 
      .attr("tabIndex", "-1").css({ 'cursor': 'pointer', 'vertical-align': 'middle', 'padding-left': '3px', 'padding-bottom': '4px' }); 

//new code that sort of works.. eg component renders fine, but fails server side 
      //$(elem).will_pickdate({ 
      // timePicker: true, 
      // format: 'Y/m/d H:i', 
      // inputOutputFormat: 'Y/m/d H:i', 
      // militaryTime: true, 
      // allowEmpty: true, 
      // startView:'day', 
      // onSelect: function (date) { 

      //  if (OnClose != null) 
      //   OnClose(); 

      //  $(this).focus(); 


      //  // $('#' + display[0].id).val(new Date($(elem).val())); 
      // //  $('#' + display[0].id+ '_display').val(new Date($(elem).val())); 
      //  // alert($('#' + display[0].id).val()); 
      // } 
      //}); 

     }, 100);} 

マイaddメソッド。 Iv'eが気づい何

public ActionResult Edit(Down_Time_Capture viewModel, FormCollection formCollection) 
    { 
     Down_Time_CaptureRepository repository = new Down_Time_CaptureRepository(); 

     try 
     { 
      if (!ModelState.IsValid) 
       return ReturnValidationFailure(ViewData.ModelState.Values); 

      int item_id = Convert.ToInt32(formCollection["id"]); 

      var model = repository.Where(o => o.DTCP_ID == item_id).SingleOrDefault(); 

      if (model == null) 
      { 
       //append any error code to allow jqgrid modal to handle error display 
       Response.StatusCode = 400; 
       return Json("Record not found.", JsonRequestBehavior.AllowGet); 
      }    

    ====> //code fails here, model tries to get updated but dies 
      if (TryUpdateModel(model, formCollection.ToValueProvider())) 
      { 
       repository.Edit(model, User.Identity.Name); 
       repository.Save(); 
       return Json("Updated successfully.", JsonRequestBehavior.AllowGet); 
      } 
      else 
      { 
       return ReturnValidationFailure(ViewData.ModelState.Values); 
      } 
     } 
     catch (Exception ex) 
     { 
      ... 
     } 

    } 

ビューモデルが有効であると日時書式で値が含まれていることですが、私はデシベルから私のモデルを更新しようとすると、それは次のようなメッセージで失敗します。入力する「可能System.String」

*タイプからパラメータ変換「..Portal.Models.Down_Time_Capture」は型コンバータは、これらのタイプ間で変換することができないために失敗した。*

Iは、値を変換しようとしました私のjavascript/jqueryの日付書式を入力し、Date Inputフィールドに追加しますが、それでも文字列として提出します

必要な場合は他の情報を提供しますが、これは奇妙なものです:

更新日:

私のビューにはjqgridコンポーネントのhtmlしか含まれていません。私は以下のjsfiddleリンクを追加しました。

Link To JsFiddle - Includes code for both datepickers

+0

、あなたのモデルを示し、見てもらえますか? –

+0

標準のEF生成モデルです。明日モデルコードを掲示しなければなりません...リフトクラブは出発しています:P haha​​。 ビューの更新が遅い –

+0

表示されているものは表示ではありません。それはいくつかのJavaScriptです。だから、明日までその見解を見るために待たなければならないだろう。 –

答えて

1

通常、ビューモデルのアプローチを使用する場合、あなたが永続オブジェクトにビューモデルから取り込まれた値を移動させる(例えばAutomapperなど)マッパーを使用します。あなたがやっていることは、キャプチャされた値をビューモデルにバインドさせることです。次に、Down_Time_Captureインスタンスを投げ捨てて、フォームからDown_Time_CaptureRepositoryによって返されるタイプにすべてバインドします(Down_Time_Captureではありません。その場合、あなたは仕事を二倍にしています)。 (値は文字列として、ワイヤの上に来るこれwill_pickdateコンポーネントが有効に渡ってDateTime値を送信するように見えるん

public ActionResult Edit(int id) 
    { 
     Down_Time_CaptureRepository repository = new Down_Time_CaptureRepository(); 

     var model = repository.Where(o => i.DTCP_ID == id).SingleOrDefault(); 

     if (model == null) 
      { 
       //append any error code to allow jqgrid modal to handle error display 
       Response.StatusCode = 400; 
       return Json("Record not found.", JsonRequestBehavior.AllowGet); 
      } 


      if (TryUpdateModel(model)) 
      { 
       repository.Edit(model, User.Identity.Name); 
       repository.Save(); 
       return Json("Updated successfully.", JsonRequestBehavior.AllowGet); 
      } 

      return ReturnValidationFailure(ViewData.ModelState.Values); 
    } 

、その後、MVCのバインダー:

まず者は、少し試してみて、あなたの行動をクリーンアップしましょうフォームフィールドの名前がバインドされているモデルのプロパティ名と一致すると、値がDateTimeに変換されます)。

+0

クール! "System.String型から '.....'型へのパラメータ変換は同じエラーを返すが、私のコードを記述/構造化するための良い方法を提供すること(そして私が何をやったのか説明すること)に関しては、ありがとう。私はそれを私のデフォルトのテンプレートなどに適用します。MVCの学習はかなり手間がかかっています。しかし、私はそこに行く –

+0

あなたはモデルクラスを投稿できますか? – HackedByChinese

+0

私は実際に私が好きな解決策を見つけました。あなたのオートマッパの提案に基づいて、読んだことに基づいて... "ValueInjecter"と呼ばれるものが見つかりました。これにより、受け取った値をdatetimeに変換することができました。また、私はクラステンプレートの再構成を促しました... 私は答えとして投稿します –

1

私のコントローラメソッドの変更を終了しました。

私はジェネリックスを使用してそれを...しようとしたいと思います。ジェネリック。それ自体はまったく新しい質問です。

 [HttpPost] 
     [AuthorizeAD] 
     public ActionResult Edit(long id, VM_Down_Time_Capture viewModel) 
     { 
      using (Down_Time_CaptureRepository repository = new Down_Time_CaptureRepository()) 
      { 
       //checks to see if data is valid 
       if (!ModelState.IsValid) 
        return ReturnValidationFailure(ViewData.ModelState.Values); 

       //find model to update 
       var model = repository.Where(o => o.DTCP_ID == id).SingleOrDefault(); 

       if (model == null) 
        RecordNotFoundError(); 

       //update model using value injector 
       model.InjectFrom(new Me().Ignore(new[] { "DTCP_ID" }), viewModel).InjectFrom<StringToDate>(viewModel); 

       //perform edit 
       string mserMsg = repository.Edit(model, User.Identity.Name); 

       //notify user of any errors/notifications 
       if (!string.IsNullOrEmpty(mserMsg)) 
        return ReturnCustomValidationFailure(Server.HtmlEncode(mserMsg)); 

       //apply changes to db 
       repository.Save(); 
       return Json("Updated successfully.", JsonRequestBehavior.AllowGet); 
      } 
     } 

ValueInjectorヘルパーコード

public class StringToDate : LoopValueInjection 
    { 
     //by default is sourceType == targetType; override to change behaviour 
     protected override bool TypesMatch(Type sourceType, Type targetType) 
     { 
      return sourceType == typeof(string) 
        && targetType == typeof(DateTime); 
     } 

     //by default is return sourcePropertyValue; override to change behaviour 
     protected override object SetValue(object sourcePropertyValue) 
     {     
      return DateTime.Parse(sourcePropertyValue.ToString()); 
     } 
    } 

    public class Me : LoopValueInjection 
    { 
     private string[] ignore; 

     public Me Ignore(string[] ignore) 
     { 
      this.ignore = ignore; 
      return this; 
     } 

     protected override bool UseSourceProp(string sourcePropName) 
     { 
      return !ignore.Contains(sourcePropName); 
     } 
    } 
関連する問題