【问题标题】:How to pass model's obejct to existing view?如何将模型对象传递给现有视图?
【发布时间】:2011-04-15 07:45:44
【问题描述】:

我正在 MVC3 中创建应用程序。我有一个会议控制器,它有一个像这样的 Create() 视图:

命名空间配置器.Controllers { 公共类 ConferenceController : BaseController

{
    public ActionResult Create()
    {           
        return View(new ConferenceModel());
    }
}

}

我在此创建视图上有一个下拉列表,其中包含产品列表。在选择特定产品时,我以这种方式在 ConferenceModel 的对象中获取该产品的详细信息:

  1. 要获取我使用 jquery 的产品 ID:

$("#ddlProductList").change(function () { $.get('/Conference/GetProductDetailByProductID/', { ProductID: $(this).val() }, function (response) { }); });

  1. 在 ConferenceController 中创建了一个函数,当下拉更改事件触发时将调用该函数。

    public ActionResult GetProductDetailByProductID(string ProductID) { 返回视图(ConferenceModel.GetProductDetailByProductID(ProductID)); }

  2. 在 ConferenceModel 中创建一个函数,根据 ProductID 从数据库中获取产品详细信息:

    public static ConferenceModel GetProductDetailByProductID(string ProductID)
    {
        ConferenceModel obj = new ConferenceModel();
    
        // Logic goes here to to get the details of product on the basis of productID and returning the object.
    
        return obj;
    }
    
  3. 当我尝试检查此功能时,它给我的错误是它没有找到任何视图来显示此部分 COnferenceController 页面上的数据:

    public ActionResult GetProductDetailByProductID(string ProductID)
    {
        return View(ConferenceModel.GetProductDetailByProductID(ProductID));
    }
    
  4. 我的问题是我是否可以使用现有的 Create() 视图来显示数据,或者我必须使用以下名称创建另一个视图:GetProductDetailByProductID()

谁知道这个问题,请帮助我。

【问题讨论】:

    标签: asp.net-mvc-3


    【解决方案1】:

    您可以使用

    指定视图名称
    return View("viewname", model)
    

    默认情况下,操作的名称用作视图名称。

    【讨论】:

      【解决方案2】:

      View 方法有一个重载,允许您指定视图名称:

      return View("Create", ConferenceModel.GetProductDetailByProductID(ProductID));

      此处的文档:http://msdn.microsoft.com/en-us/library/dd460310.aspx

      【讨论】:

        【解决方案3】:

        您希望使用 jQuery 从客户端脚本中获取产品详细信息。

        而不是回复:

        public ActionResult GetProductDetailByProductID(string ProductID)
        {
            return View(ConferenceModel.GetProductDetailByProductID(ProductID));
        }
        

        为什么不简单地返回一个 JSON 字符串?

        public JsonResult GetProductDetailByProductID(string ProductID)
        {
            return this.Json(ConferenceModel.GetProductDetailByProductID(ProductID));
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2013-07-20
          • 1970-01-01
          • 2011-08-10
          • 2020-02-23
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多