控件未在ASP.net MVC中刷新

时间:2009-07-27 05:46:04

标签: asp.net-mvc

我正在研究Microsoft ASP MVC框架。这是我的页面奇怪的事情。

我在页面上有两个下拉列表。第一个发布表单,将参数传递给控制器​​。控制器更新第二个下拉列表和其他控件,如两个文本框。我确实将数据传递给viewdata。并将它们分配给控件(SelectList到DropDownList,字符串到TextBox)。但那些讽刺仍然像以前一样。我该如何解决这个问题?提前谢谢!

此致

编辑:

谢谢!这是我的代码:

查看:

    <script type="text/javascript" language="javascript">
    function Postback() {
        var control = document.getElementById("Country");
        var parameter = document.getElementById("CountryName");

        parameter.value = control.value;

        document.forms.item(0).submit();

    }

</script>

<%Html.BeginForm();%>

    <fieldset>
        <legend>Fields</legend>
        <p style="height: 0px">
        <input type="hidden" id="CountryName" name="CountryName" value="" />
        </p>
        <p>
            <label for="Country">Country:</label>
            <%=Html.DropDownList("Country", (SelectList)ViewData["Countries"]), new { onchange="Postback()" })%>
        </p>
        <p>
            <label for="State">State:</label>
            <%=Html.DropDownList("State", (SelectList)ViewData["States"] )%>
            </p>
        <p>
            <label for="Brief Intro">Introduction:</label>
            <%= Html.TextBox("Intro", ViewData["Introduction"]) %>
        </p>
        <p>
            <input type="submit" value="Save" />
        </p>
    </fieldset>

<%Html.EndForm(); %>

控制器:

public ActionResult Info()
{
    ViewData["Countries"] = new SelectList(_db.Coutries.ToList(), "Id", "Name");
    return View();
}

AcceptVerbs(HttpVerbs.Post)]
public ActionResult Info(int country)
{
    ViewData["Countries"] = new SelectList(_db.Coutries.ToList(), "Id", "Name", country);

    ViewData["States"] = new SelectList(_db.States.Where(s => s.countryid == country).ToList(), "Id", "Name");

    ViewData["Info"] = _db.CountryInfo.SingleOrDefault(info => info.countryid == country).Content;

    return View();
}

编辑:在第二个控制器中调用ModelState.Clear()修复该问题。感谢所有提出建议的人!真的很感谢!

2 个答案:

答案 0 :(得分:1)

使用强类型IEnumerable<SelectListItem> - 我认为它优于SelectList。试试这个(你检查了调试器中的int country参数吗?):

AcceptVerbs(HttpVerbs.Post)]
public ActionResult Info(int country)
{
    ViewData["Countries"] = _db.Countries.Select(x => new SelectListItem {
        Text = x.Name,
        Value = x.Id, // or countryId ?
        Selected = x.Id == country 
    }).ToList();

    ViewData["States"] = _db.States.Where(s => s.countryid == country)
        .Select(x => new SelectListItem {
            Text = x.Name,
            Value = x.Id
        }).ToList();

    // Info? or Intro? (there is only Intro in View)
    ViewData["Info"] = _db.CountryInfo.SingleOrDefault(info => info.countryid == country).Content;

    return View();
}

希望这有帮助

答案 1 :(得分:0)

您是否在SelectList中设置selectedValue(下面代码段中构造函数的第二个参数)?

var items = new SelectList(new List<string> {"one", "two", "three"}, "two");