asp.net mvc的:什么是从控制器返回HTML刷新选择列表中正确的方法是什么? [英] asp.net mvc: What is the correct way to return html from controller to refresh select list?

查看:103
本文介绍了asp.net mvc的:什么是从控制器返回HTML刷新选择列表中正确的方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是新来的ASP.NET MVC,尤其是Ajax操作。我有添加项目到一个下拉列表中一个jQuery对话框的形式。这帖子到控制器的动作。

I am new to ASP.NET MVC, particularly ajax operations. I have a form with a jquery dialog for adding items to a drop-down list. This posts to the controller action.

如果没有(即空白法)从控制器操作返回页面就会返回已经更新了数据库,但显然没有chnage到窗体。什么是在更新下拉与添加的ID /值列表,然后选择项目的最佳实践。
我觉得我的选择是:

If nothing (ie void method) is returned from the Controller Action the page returns having updated the database, but obviously there no chnage to the form. What would be the best practice in updating the drop down list with the added id/value and selecting the item. I think my options are:

1)构造并返回的HTML手动,构成了新的<选择> 标签
[这将是很容易和工作,但好像我失去了一些东西]

1) Construct and return the html manually that makes up the new <select> tag [this would be easy enough and work, but seems like I am missing something]

2)用某种助手的构造新的html
[这似乎有道理]

2) Use some kind of "helper" to construct the new html [This seems to make sense]

3)只返回ID /价值,这添加到列表中,选择项目
[这似乎是审议该项目时矫枉过正,需要放置在正确的顺序等]

3) Only return the id/value and add this to the list and select the item [This seems like an overkill considering the item needs to be placed in the correct order etc]

4)使用某种管窥
[这是否意味着创造的ascx控件中的其他形式?不知道如何做到这一点影响提交的主要形式及其对?此外,除非这在参数传递(不知道如何做的多数民众赞成)也许是2选择是可重用的?]

更新:

说完四处张望了一下,似乎是生成HTML withing控制器是不是一个好主意。我已经看到,渲染partialviews到我的猜测是我需要和分离的担忧(因为HTML位在ASCX)字符串其他职位。是否这是很好的做法有意见。

Having looked around a bit, it seems that generating html withing the controller is not a good idea. I have seen other posts that render partialviews to strings which I guess is what I need and separates concerns (since the html bits are in the ascx). Any comments on whether that is good practice.

推荐答案

返回一个 JsonResult 与所有的项目是最通用和最带宽密集型解决方案,只要你很高兴通过jQuery的列表进行迭代和更新您的下拉列表中。

Returning a JsonResult with all the items is the most versatile and least-bandwidth intensive solution as long as you are happy to iterate through the list in jQuery and update your drop-down list.

使用局部视图是HTML,你可以.load(...),直接到你的选择不错,但通用性较差。

Using a partial view is nice for HTML that you can .load(...) directly into your select, but less versatile.

我会去的 JsonResult

public JsonResult UpdateItem(string sItem)
{
    // 1. Insert new item into database if not exist...
    // {update code here}

    // 2. retrieve items from database:
    IEnumerable<Item> Items = GetItems();

    // 3. return enumerable list in JSON format:
    return new JsonResult{ Data = new {Items = Items, Result = "OK" }};
}

在客户端:

通过项目阵列迭代,并添加项目到列表中。

On client-side:

Iterate through Items array and add the items to your list.

这篇关于asp.net mvc的:什么是从控制器返回HTML刷新选择列表中正确的方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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