0

我正在尝试构建一个功能,我需要在我们的应用程序中创建候选人的个人资料。创建候选人的个人资料有两个步骤/用户界面:

1 - 创建模板...用户输入候选人信息的地方。

2 - 预览模板...一旦用户将个人资料添加到我们的系统,将在其中预览他们的个人资料的外观。

我已经通过一个名为“CandidateController”的控制器创建了支持这些 UI 的视图,该控制器包含一些操作方法:

1- [HttpGet]“创建”返回一个创建模板。

[HttpGet]
public ViewResult Create()

2- [HttpPost] 返回预览模板的“预览”。

 [HttpPost]
 public ActionResult Preview(ProfileViewModel viewModel)

现在我需要实现的是在 Create 模板中有一个按钮/链接,它将调用控制器中的操作方法 [HttpPost] Preview。

挑战 我还想知道如果能够从第一个创建模板调用 HttpPost Preview 操作方法,模型绑定器是否可以为我加载 ViewModel 对象。

我正在寻找有关如何最好地实现这种功能的建议/帮助。

任何帮助将不胜感激。

4

2 回答 2

3

挑战我还想知道如果能够从第一个创建模板调用 HttpPost Preview 操作方法,模型绑定器是否可以为我加载 ViewModel 对象。

You could use either a standard form or an AJAX call to invoke the Preview POST action and pass all the property values of the view model then. All the values you pass in this request will be the values that will be bound by the default model binder. Here's an article explaining how the default model binder expects the parameters to be named for more complex structure such as lists and dictionaries.

Example with AJAX:

$.ajax({
    url: '@Url.Action("Preview")',
    type: 'POST',
    data: { Prop1: 'value 1', Prop2: 'value 2' },
    success: function(result) {
        // TODO: do something with the result returned from the POST action
    }
});

If you don't want to use AJAX you could use a standard form with hidden fields:

@using (Html.BeginForm())
{
    @Html.Hidden("Prop1", "value 1")
    @Html.Hidden("Prop2", "value 2")
    ...
    <button type="submit">Preview</button>
}
于 2011-12-09T19:18:43.647 回答
1

OK so here are the options that I had to get around:

  • As Darin suggested you may go with the unobtrusive way by using $.ajax(options), however the thing is you might want to go this way only if you want to do a partial page update or if you want to work on updating/dumping new html in the same view.
  • And if you don't want to use the Ajax, instead of using Hidden fields, you can simply use the TempData property in MVC, this is how I implemented my targeted functionality using TempData. p.s.below...

    [HttpPost]       
    public ActionResult Create(ViewModel viewModel)
    {
        this.TempData["profile"] = viewModel;
        return RedirectToAction("Preview");
    }
    
    
    public ActionResult Preview()
    {            
    
        if (TempData["profile"] != null)
        {
            return View((ViewModel)TempData["profile"]);
        }
    
        // Handle invalid request...
        return null;
    }
    

So, this solution worked pretty well for me, where I did not write any JavaScript or unnecessary HTML. AND thanks Darin for directing me to a starting point.

于 2011-12-12T18:51:22.030 回答