0

FormCollectionを介して渡された情報に基づいてモデルを正しく更新するためのUpdateModel関数を取得できないため、何かが正しく設定されていない必要があります。

私の見解は次のようになります:

@model NSLM.Models.Person
@{
    ViewBag.Title = "MVC Example";
}
<h2>My MVC Model</h2>
<fieldset>
    <legend>Person</legend>
    @using(@Html.BeginForm())
    {
        <p>ID: @Html.TextBox("ID", Model.ID)</p>
        <p>Forename: @Html.TextBox("Forename", Model.Forename)</p>
        <p>Surname: @Html.TextBox("Surname", Model.Surname)</p>
        <input type="submit" value="Submit" />
    }  
</fieldset>

私のモデルは:

    namespace NSLM.Models
    {
        public class Person
        {
            public int ID;
            public string Forename;
            public string Surname;
        }
    }

そして私のコントローラーは:

        [HttpPost]
        public ActionResult Details(FormCollection collection)
        {
            try
            {
                // TODO: Add update logic here                
                Models.Person m = new Models.Person();

                // This doesn't work i.e. the model is not updated with the form values
                TryUpdateModel(m);

                // This does work 
                int.TryParse(Request.Form["ID"], out m.ID);
                m.Forename = Request.Form["Forename"];
                m.Surname = Request.Form["Surname"];

                return View(m);
            }
            catch
            {
                return View();
            }
        }

各プロパティを手動で割り当てると正常に機能することがわかりますが、モデルがフォーム値で更新されるように設定していないものは何ですか?

ありがとう、

マーク

4

3 に答える 3

1

呼び出しがアクションメソッドに到達するまでに、自動モデルバインディングはすでに実行されています。アクションメソッドの入力パラメーターを変更して、Personインスタンスを受け入れてみてください。その場合、モデルバインダーはインスタンスを作成し、フォームから渡された値からインスタンスを設定しようとします。

于 2012-08-08T13:12:12.067 に答える
1

フィールドをモデルのプロパティに置き換えます。例:

namespace NSLM.Models
{
    public class Person
    {
        public int ID {get; set;}
        public string Forename {get; set;}
        public string Surname {get; set;}
    }
}
于 2012-08-09T06:36:55.867 に答える
0

これを試して :

見る :

@model NSLM.Models.Person
@{
    ViewBag.Title = "MVC Example";
}
<h2>My MVC Model</h2>
<fieldset>
    <legend>Person</legend>
    @using(@Html.BeginForm())
    {
         @Html.HiddenFor(model => model.ID)

        <p>Forename: @Html.EditorFor(model => model.Name)
            @Html.ValidationMessageFor(model => model.Name)
        </p>
        <p>Surname: @Html.EditorFor(model => model.Surname)
            @Html.ValidationMessageFor(model => model.Surname)
        </p>
        <input type="submit" value="Submit" />
    }  
</fieldset>

コントローラー:

[HttpPost]
public ActionResult Details(Person p)
{
    if (ModelState.IsValid)
    {
        db.Entry(p).State = EntityState.Modified;
        db.SaveChanges();
        return RedirectToAction("Index");
    }
    return View(p);
}
于 2012-08-08T13:18:44.227 に答える