开发者

MVC3 Strongly typed partial view model binding

I have a strongly typed view, Edit, with a model named OrderModel. In this view, I am using a strongly typed partial view that has a model named OrderTypeModel. The partial view, _OrderTypeAutoComplete, that contains a jqueryui autocomplete textbox. If I render the view with this code,

public ActionResult Edit(){
    return View();
}

My Edit view contains the following Razor markup

<div class="editor-field">
    @Html.Partial("_OrderTypeAutoComplete")
    @Html.HiddenFor(model => model.OrderTypeID)
    @Html.ValidationMessageFor(m => m.OrderTypeID)
</div>

My Partial view contains this razor markup

@{
    Layout = null;
}
<script src="@Url.Content("~/Scripts/jquery-ui-1.8.11.min.js")" type="text/javascript"></script>
@Html.AutoCompleteFor(model => model.OrderTypeID, x =>  x.OrderType, "Items","Orders")

When I render this, all is great and my autocomplete works great (using an auto-complete extension). Anyway, I needed to initialize something in my initial OrderModel, so I changed the code in my controller to this.

public ActionRe开发者_如何学运维sult Edit(){
    return View(OrderService.GetInitializedOrderModel()); //returns a new OrderModel
}

Now when I render the view, I get the exception: The model item passed into the dictionary is of type 'Testing.Models.OrderModel', but this dictionary requires a model item of type 'Testing.Models.OrderTypeModel'.

on this line in my view @Html.Partial("_OrderTypeAutoComplete")

It seems the Razor engine will create the OrderModel for the view and the OrderTypeModel for the partial view fine when I haven't supplied the OrderModel. This will give the same results.

public ActionResult Edit(){
    return View(new OrderModel())
}

I'm new to MVC so I'm not sure what's going on here. I'm simply trying to provide some simple dropdown values for my view in the OrderModel model that are small enough that I don't require a jquery postback to get. That's the values I'm initialing in my model for the Http Get on my Edit action.

Any help would be appreciated. Thanks.


The class definitions for your model classes are missing from the example so I can't tell exactly what is going on, but...

The @Html.Partial() method has a few overloads:

@Html.Partial(string)
@Html.Partial(string, Object)
@Html.Partial(string, ViewDataDictionary)
@Html.Partial(string, Object, ViewDataDictionary)

The first three overloads are all just "aliases" for the last one - when all's said and done it is the last one that gets called.

When you call the @Html.Partial(string) and do not pass a model value or ViewDataDictionary, ASP.NET MVC will just pass in the ViewDataDictionary for the current view (i.e. this.ViewData).

I other words, a call to:

@Html.Partial(string)

Is essentially equivalent to:

@Html.Partial(string, this.ViewData)

... and in your case, this.ViewData is of type OrderModel, not OrderModelType.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜