开发者

Do I need a custom modelbinder for my Create Action?

I have been doing a bit of research on this but, I am having a little trouble understanding when modelbinding is needed in MVC 3. I have created a ViewModel to supply data to my Create view.

public class InvitationRequestViewModel
{
    public InvitationRequest InvitationRequest { get; private set; }

    public IEnumerable<SelectListItem> EventsList { get; private set; }

    public string EventId { get; set; }

    public InvitationRequestViewModel(InvitationRequest request)
    {
        InvitationRequest = request;
        EventsList = new SelectList(MyRepositoryAndFactory.Instance.FindAllEvents()
                .Select(events => new SelectListItem 
                { 
                    Value = events.ID.ToString(),
                    Text = String.Format("{0} - {1} - {2}", events.Name, events.Location, events.StartDate.ToShortDateString())
                }
            ), "Value", "Text");
    }
}

My InvitationRequest controller has the following Action methods

public ActionResult Create()
    {
        InvitationRequest request = new InvitationRequest(User.Identity.Name);

        return View(new InvitationRequestViewModel(request));
    } 

    [HttpPost]
    public ActionResult Create(InvitationRequestViewModel newInvitationRequest)
    {
        try
        {
            if (!ModelState.IsValid) return View(newInvitationRequest);

            newInvitationRequest.InvitationRequest.Save();
            MyRepositoryAndFactory.Instance.CommitTransaction();
            return RedirectToAction("Index");
        }
        catch
        {
            ModelState.AddModelError("","Invitation Request could not be created");
        }

        return View(newInvitationRequest);
    }

I can reach the Create view with no problems and the DDL is populated with a list of available events. My problem is that I was expecting the InvitationRequestViewMo开发者_如何转开发del to be mapped to the HttpPost Create method. Instead, I just get an error saying "The website cannot display the page". When I use the signature:

public ActionResult Create(FormCollection collection){ }

then I can see the posted values. I had hoped not to have to do my own mapping code in the controller.

Is a custom ModelBinder the answer?

EDIT I am using a strongly typed View of type InvitationRequestViewModel and this is the DDL code

<div class="editor-label">
        @Html.LabelFor(model => model.InvitationRequest.Event)
    </div>
    <div class="editor-field">
        @Html.DropDownListFor(x => x.EventId, Model.EventsList)
    </div>


You have to specify a parameterless constructor for the InvitationRequestViewModel so the default model binder can instantiate it.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜