6

私はこの次のコードを持っています:

[HttpPost]
public JsonResult Index2(FormCollection fc)
{
    var goalcardWithPlannedDate = repository.GetUserGoalCardWithPlannedDate();
    return Json(goalcardWithPlannedDate.Select(x => new GoalCardViewModel(x)));
}

しかし、代わりに部分ビューで使用したいのですが、どうすればよいですか?

4

2 に答える 2

2

必要なものを正しく理解している場合は、次のことを試してください。

public JsonResult Index2(FormCollection fc)
{
    var goalcardWithPlannedDate = repository.GetUserGoalCardWithPlannedDate();
    return Json(goalcardWithPlannedDate.Select(x => new GoalCardViewModel(x)), "text/html", JsonRequestBehavior.AllowGet);
}

を使用してこのアクションを呼び出すと、JsonResult が応答全体のコンテンツ タイプをオーバーライドするため、c コンテンツ タイプを設定することが重要ですHtml.RenderAction。これは良い解決策ではありませんが、場合によってはうまくいきます。

代わりに、より良い解決策を試すこともできます:

var scriptSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();
var jsonString = scriptSerializer.Serialize(goalcardWithPlannedDate.Select(x => new GoalCardViewModel(x)));

次に、文字列表現で必要なことをすべて行うことができます。その中で実際にJsonResult行っていることです。ところで、ここでは任意の json シリアライザーを使用できます。

クライアントでアクセスしたい場合。コードを変更する必要はありません。jQuery を使用する場合:

$.post('<%= Url.Action("Index2") %>', { /* your data */ }, function(json) { /* actions with json */ }, 'json')

ビューモデルに渡したい場合:

[HttpPost]
public ActionResult Index2(FormCollection fc)
{
    var goalcardWithPlannedDate = repository.GetUserGoalCardWithPlannedDate();
    return PartialView(new MyModel { Data = goalcardWithPlannedDate.Select(x => new GoalCardViewModel(x)) });
}
于 2012-05-28T10:35:31.960 に答える
0

Json の代わりに部分的なビューを返すこともできます。

[HttpPost]
public ActionResult Index2(FormCollection fc)
{
   var goalcardWithPlannedDate = repository.GetUserGoalCardWithPlannedDate();
   return PartialView(goalcardWithPlannedDate.Select(x => new GoalCardViewModel(x)));
}
于 2012-05-28T10:40:47.667 に答える