MVC无法加载资源:服务器响应状态为500(内部服务器错误) [英] MVC Failed to load resource: the server responded with a status of 500 (Internal Server Error)

查看:402
本文介绍了MVC无法加载资源:服务器响应状态为500(内部服务器错误)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的第一个MVC项目有问题.选择医生类型的DropDownList时,我尝试更改姓的DropDownList值.我认为我的行动正在奏效.但是我不能在结果中使用结果. 这是我的代码:

I have problem with my first MVC project. I'm trying to change values of DropDownList of surnames when select DropDownList of doctor types. I think my action is working. But I cannot use result in view. Here my codes:

$(function () {
            $('select#mCB').change(function () {
                var docId = $(this).val();

                $.ajax({
                    dataType: 'json',
                    data: 'spec=' + docId,
                    method: 'GET',
                    url: 'LoadDoctors',
                    success: function (data) {
                        $.each(data, function (key, Docs) {
                            $('select#shCB').append('<option value="0">Select One</option>');

                            $.each(Docs, function (index, docc) {
                                $('select#shCB').append(
                                    '<option value="' + docc.Id + '">' + docc.Name + '</option>');
                            });
                        });
                    },
                    error: function (docID) {

                        alert(' Error !');
            }
                });
            });
        });

动作:

public static List<Docs> GetDoctorBySpec(string spec)
        {
            List<Docs> list = new List<Docs>();

            string query = "select ID, Familiyasi, Speciality from Doktorlar where Speciality=@spec";
            SqlConnection Connection = new SqlConnection(DataBase.ConnectionString);
            Connection.Open();
            SqlCommand cmd = new SqlCommand(query, Connection);
            cmd.Parameters.Add("@spec", spec);
            SqlDataReader dr = cmd.ExecuteReader();

            while (dr.Read())
            {
                list.Add(new Docs
                { 
                    Id = dr.GetString(0),
                    Name = dr.GetString(1)

                });
            }

            return list;
        }
enter code here
enter code here
[HttpGet]
    public ActionResult LoadDoctors(string spec)
    {
        List<Docs> list = DoctorsService.GetDoctorBySpec(spec);

        if (list == null)
        {
            return Json(null);
        }

        return Json(list);

    }

这是我的DropDownLists:

And here my DropDownLists:

<div class="editor-label">
                @Html.LabelFor(model => model.DoktorTuri)
            </div>
            <div class="editor-field">
                @Html.DropDownListFor(model => model.DoktorTuri, new SelectList(ViewBag.Vrachlar), new { @id = "mCB", @class = "vrachlar" })
            </div>

            <div class="editor-label">
                @Html.LabelFor(model => model.Shifokori)
            </div>
            <div class="editor-field">
                @Html.DropDownListFor(model => model.Shifokori, Enumerable.Empty<SelectListItem>(), new { @id = "shCB", @class = "vrachlar" })
            </div>

我的错误在哪里?感谢您的回答

Where is my mistake? Thanks for answers

推荐答案

500 (Internal Server Error)几乎总是意味着您在服务器上引发了异常.最好的猜测是您的情况,因为您的方法

A 500 (Internal Server Error) almost always means that your throwing an exception on the server. Best guess is in your case it's because your method

DoctorsService.GetDoctorBySpec(spec);

不接受null作为参数,并且spec的值是null,因为您永远不会将其值传递给控制器​​.正如stann1指出的那样,您的ajax选项必须为

does not accept null as a parameter and the value of spec is null because your never pass it value to the controller. As stann1 has noted your ajax option needs to be

data: {spec: docId},

此外,您没有指定JsonRequestBehavior.AllowGet参数,这意味着该方法将失败.

In addition, you do not specify the JsonRequestBehavior.AllowGet parameter which means the method will fail.

所有这些都可以通过在服务器上调试代码以及​​使用浏览器工具(尤其是Network标签以查看正在发送和接收的内容以及错误消息)来轻松地确定.

All of this can be easily determined by debugging your code, both on the server and by using your browser tools (in particular the Network tab to see what is being sent and received along with error messages)

但这只是您的代码中许多问题之一.

However this is only one of many problems with your code.

首先,除非Docs仅包含2个属性(该选项的value属性和显示文本所需的值),否则您不必要地通过向客户端发送大量数据来浪费带宽和降低性能,而这永远不会用过的.而是发送一组匿名对象

Firstly, unless Docs contains only 2 properties (the values you need for the option's value attribute and display text), your unnecessarily wasting bandwidth and degrading performance by sending a whole lot of data to the client which is never used. Instead, send a collection of anonymous objects

[HttpGet]
public ActionResult LoadDoctors(string spec)
{
  List<Docs> list = DoctorsService.GetDoctorBySpec(spec);
  if (list == null)
  {
    return Json(null, JsonRequestBehavior.AllowGet);
  }
  var data = list.Select(d => new
  {
    Value = d.Id,
    Text = d.Name
  });
  return Json(data, JsonRequestBehavior.AllowGet);
}

接下来,您的脚本将只生成多个<option value="0">Select One</option>元素(集合中的每个项目一个),因为$.each(data, function (key, Docs) {中的data是您的集合,而Docs是集合中的项目.第二个$.each()函数将永远不会产生任何结果,因为Docs不是集合.

Next, your script will only ever generate multiple <option value="0">Select One</option> elements (one for each item in the collection) because data in $.each(data, function (key, Docs) { is your collection, and Docs is the item in the collection. Your second $.each() function will never produce anything because Docs is not a collection.

您的脚本应该是(请注意,我使用的是较短版本的$.getJSON()而不是较长的$.ajax(),并且还使用了html帮助程序生成的默认id属性-尚不清楚您为什么要更改id正在使用new { id = "mCB" }?)

You script should be (note I have use the short version $.getJSON() rather than the longer $.ajax() and also used the default id attributes generated by the html helpers - its not clear why you would want to change the id's using new { id = "mCB" }?)

var url = '@Url.Action("LoadDoctors")'; // never hard code your url's
var shifokori = $('#Shifokori'); // cache it
$('#DoktorTuri').change(function () {
  $.getJSON(url, { spec: $(this).val() }, function(data) {
    if (!data) { // only necessary depending on the version of jquery
      // oops
    }
    // clear existing options and append empty option with NULL value (not zero) 
    // so validation will work
    shifokori.empty().append($('<option></option>').val('').text('Select One'));
    $.each(data, function (index, doc) {
      shifokori.append($('<option></option>').val(doc.Value).text(doc.Text));
    });
  }).fail(function (result) {
    // oops
  });
});

这篇关于MVC无法加载资源:服务器响应状态为500(内部服务器错误)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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