绑定模型变量在ASP.NET MVC3的操作方法 [英] Binding the Model variable to an Action Method in ASP.NET MVC3

查看:88
本文介绍了绑定模型变量在ASP.NET MVC3的操作方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个控制器的HomeController 具有以下操作方式

I have a controller HomeController with the following action method:

[HttpPost] 
public ActionResult DisplayData(MyViewModel myViewModel)
{
   // Do something with myViewModel           
}

视图模型

public class MyViewModel
{
    public string Name { get; set; }
    public string Surname { get; set; }
    public bool IsPeriod { get; set; }
}

和下面的查看

@model AppName.ViewModels.MyViewModel

@{ Html.RenderPartial("MyPartialView", Model);  }

<img src="@Url.Action("DisplayData", "Home", new { myViewModel = Model })" alt="Image" />

我用它是如何描述的Url.Action的这里但我得到的DisplayData操作方法为空。在源$ C ​​$ C我:

I use the Url.Action how it is described here but what I get in the DisplayData action method is null. In the source code I got:

<img src="/Home/DisplayData?filters=AppName.ViewModels.MyViewModel" alt="Image" />

所以它实际上不是传递的值的类型。

so it is passing actually the type instead of the values.

视图模型而不是正确地传递到局部视图。我在做什么错了?

The ViewModel instead is correctly passed to the partial view. What am I doing wrong?

推荐答案

我通常添加以下到我的模型:

I usually add the following to my model:

public class MyViewModel
{
    public string Name { get; set; }
    public string Surname { get; set; }
    public bool IsPeriod { get; set; }

    public RouteValueDictionary RouteValues
    {
        get
        {
            var rvd = new RouteValueDictionary();
            rvd["name"] = Name;
            rvd["surname"] = Surname;
            rvd["isPeriod"] = IsPeriod;
            return rvd;
        }
    }
}

然后,你可以简单地使用RouteValues​​财产在Url.Action()调用。

Then you can simply use the RouteValues property in your Url.Action() call.

<img src="@Url.Action("DisplayData", "Home", Model.RouteValues)" alt="Image" />

或者,如果你的preFER以下(明确的)code,忽略​​模式的变化,简单地做到这一点:

Or if your prefer less (explicit) code, ignore the model changes and simply do this:

<img src="@Url.Action("DisplayData", "Home", new RouteValueDictionary(Model)" alt="Image" />

这篇关于绑定模型变量在ASP.NET MVC3的操作方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆