简体   繁体   English

根据下拉列表项选择更改MVC中的视图

[英]Change View in mvc based on dropdownlist item selection

I have a dropdownlist on a View as: 我在View上有一个下拉列表:

<p>
@Html.DropDownList("Status", new List<SelectListItem>
    {
    new SelectListItem{ Text = "Show Active", Value = "0" },
    new SelectListItem{ Text = "Show Deleted", Value = "1" }},
    new
         {
             onchange = @"
        var form = document.forms[0];
        form.action='deletedDistricts';
        form.submit();"
         })

and I am referring it to controller action as: 我指的是控制器动作:

[HttpPost]
    [ActionName("deletedDistricts")]
    public ActionResult deletedDistricts()
    {
        var d = hc.deletedDistricts.ToList();
        return View(d);
    }

but JavaScript is giving a runtime error as: 但JavaScript给出的运行时错误为:

0x800a138f - JavaScript runtime error: Unable to set property 'action' of undefined or null reference 0x800a138f-JavaScript运行时错误:无法设置未定义或空引用的属性“操作”

I am not very good at JavaScript. 我不太擅长JavaScript。 Any idea why this code is throwing Null reference? 知道为什么这段代码会抛出Null引用吗?

Well I can't see that you would have a form associated with a dropdown, make sure that it's wrapped with: 好吧,我看不到您会有与下拉菜单相关联的表单,请确保将其包装为:

@using(Html.BeginForm("deletedDistricts", controllerName, FormMethod.Post)) {
    // drowpdown here
}

And remove 并删除

form.action='deletedDistricts';

conrollerName should be name of your controller as a string. conrollerName应该是控制器的名称(字符串)。

Let's read the error you are getting once again: 让我们再次阅读您得到的错误:

0x800a138f - JavaScript runtime error: Unable to set property 'action' of undefined or null reference 0x800a138f-JavaScript运行时错误:无法设置未定义或空引用的属性“操作”

OK, now let's read your code once again to see where you are attempting to set an action property. 好的,现在让我们再次阅读代码,以查看尝试在何处设置action属性。 Looks like that's happening right over here: 看起来好像正在这里发生:

form.action='deletedDistricts';

Alright, so it seems like the form instance is undefined at this stage. 好的,因此似乎在此阶段未定义form实例。 So the obvious next step you would like to look at is where is this form instance coming from. 因此,您接下来要看的显而易见的下一步是此form实例来自何处。 And you wouldn't be surprised to find this line of code of yours: 而且,您会发现自己的这一行代码不会感到惊讶:

var form = document.forms[0];

Cool, you seem to be attempting to retrieve the first <form> element in your DOM. 不错,您似乎正在尝试检索DOM中的第一个<form>元素。 But do you have such element? 但是你有这样的元素吗? Did you ever use the Html.BeginForm helper to render an HTML form? 您是否曾经使用过Html.BeginForm帮助器来呈现HTML表单? Answering those simple questions would definitely put you on the right track. 回答这些简单的问题肯定会让您走上正确的道路。 Don't hesitate to inspect the markup you are generating in the browser. 不要犹豫,检查您在浏览器中生成的标记。 I am sure this would help you figure out the missing bits. 我相信这将帮助您找出缺失的部分。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM