0

ビューのフォームを検証するのに問題があります。

私はコントローラーを持っているUpdateModel(object);ので、検証を構築する方法がわかりません。

[Required(ErrorMessage = "Please enter a contact name")]必須のすべてのプロパティを追加しました。

すべてを機能させるにはどうすればよいですか?私のコントローラーはいくつかの複雑なことをしているので。以下はコントローラーコードです。

        [HttpPost]
    public ActionResult PersistListing()
    {
        var listingView = new MaintainListingView();

        if (!string.IsNullOrEmpty(Request["Listing.Guid"]))
        {
            var dbListing = _service.GetByGuid<Listing>(Guid.Parse(Request["Listing.Guid"]));

            if (dbListing != null)
            {
                listingView.Listing = dbListing;
            }
        }

        UpdateModel(listingView);    
        RebindTranslationsDictionary(listingView.Listing);
        listingView.Listing.CategoryId = _service.GetByGuid<ListingCategory>(listingView.SelectedListingCategoryGuid).Id;
        _service.PersistEntity(listingView.Listing);
        return RedirectToAction("Edit", new { id = listingView.Listing.Guid });

    }

ベースモデルのRequired属性のコメントを解除すると、UpdateModel()を実行しようとするとエラーが発生します。

誰かがこれに対する簡単な修正を見ることができますか?

編集:私はHtml.TextBoxFor()ビューのコントロールを作成するために使用しています。

TryUpdateModelを追加しましたが、入力されたエラーメッセージでユーザーをリダイレクトする方法がわかりません。

     if (TryUpdateModel(listingView))
        {

            RebindTranslationsDictionary(listingView.Listing);

            listingView.Listing.CategoryId =
                _service.GetByGuid<ListingCategory>(listingView.SelectedListingCategoryGuid).Id;


            _service.PersistEntity(listingView.Listing); //save the ting


            return RedirectToAction("Edit", new {id = listingView.Listing.Guid});
          }

ビューにEditForModelタグが必要ですか?

4

1 に答える 1

1

例外をスローせず、検証が失敗したかどうかを知ることができるため、TryUpdateModel代わりに使用できます。UpdateModel

if (!TryUpdateModel(listingView))
{
    // there were validation errors => redisplay the view 
    // so that the user can fix those errors
    return View(listingView);
}  

// at this stage you know that validation has passed 
// and you could process the model ...
于 2012-09-20T11:34:58.387 に答える