1

私は現在asp.netmvcを勉強していて、始めたばかりで、Webフォームからmvcに移行することにしました。

私はこのコードを持っているので興味があります。モデルをreturn View(data)渡す場合と渡さない場合の違いを知りたいです。

コードは次のとおりです。

コントローラー

/* Even if I comment/remove the lines ViewBag.GenreId....... and ViewBag.ArtistId
   and just return View(); everything seems to work fine. I'm following this music store tutorial from codeplex
*/

[HttpPost]
public ActionResult Create(Album album)
{
     if (ModelState.IsValid)
     {
          db.Albums.Add(album);
          db.SaveChanges();
          return RedirectToAction("Index");  
     }
     //this will assign the values of the dropdownlist of the View
     //it will assign the values on the dropdownlist that has a name GenreId
     ViewBag.GenreId = new SelectList(db.Genres, "GenreId", "Name", album.GenreId);
     ViewBag.ArtistId = new SelectList(db.Artists, "ArtistId", "Name", album.ArtistId);
     return View(album);
}

ビューのコード

@model CodeplexMvcMusicStore.Models.Album

@{
    ViewBag.Title = "Create";
}

<h2>Create</h2>

<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>

@using (Html.BeginForm()) {
    @Html.ValidationSummary(true)
    <fieldset>
        <legend>Album</legend>

        <div class="editor-label">
            @Html.LabelFor(model => model.GenreId, "Genre")
        </div>
        <div class="editor-field">
            @Html.DropDownList("GenreId", String.Empty)
            @Html.ValidationMessageFor(model => model.GenreId)
        </div>

View(album)また、オブジェクトモデルを渡す場合と渡さない場合の違いについても知りたいと思いますView()

4

3 に答える 3

2

私の知る限り、モデルを渡さないと、ページにデータが取り込まれません。

また、フォームをポストバックするときに値をバインドする場所もわかりません。

于 2013-01-08T09:48:39.920 に答える
1

データを渡さないと、かみそりのデータにアクセスできません。return View(model)Razor Viewで使用するには、モデルをに渡す必要があります。複数のモデルを渡す必要がある場合は、ViewBagまたはViewDataを使用して渡すことができます。

あなたの質問を見ることによって。このMVCDropDownListForチュートリアルで答えを見つけることができるかもしれないと私には思えます

于 2013-01-08T12:26:19.430 に答える
0

戻り値 View(album) でオブジェクト モデルを渡さない場合、検証エラーがあったとしてもビューに表示されません。GenreId と ArtistId に ViewBag を使用しているため、Karthik によって投稿されたビュー (View() を返す) にオブジェクト モデルを渡すことなく、ビューでレンダリングできます。

于 2013-01-08T12:14:48.160 に答える