简体   繁体   English

MVC 5 ASP.NET Json 结果传递参数为空

[英]MVC 5 ASP.NET Json result passing parameter as null

I am trying to filter my dropdown from previous dropdowns but json is passing the results as null.我正在尝试从以前的下拉列表中过滤我的下拉列表,但 json 将结果作为 null 传递。 In the jquery when debugged, it shows the values of the businessunitCd and facilityCd but in the controller it shows up as null.在 jquery 调试时,它显示了 businessunitCd 和 factoryCd 的值,但在控制器中它显示为 null。

When I try to debug, it says that my SQLPersistor has an error on this line SqlDataReader dr = cmd.ExecuteReader();当我尝试调试时,它说我的 SQLPersistor 在这一行上有错误SqlDataReader dr = cmd.ExecuteReader(); and an error saying和一个错误说

they cannot find @FAC_CD他们找不到@FAC_CD

My controller:我的控制器:

public JsonResult GetProcessShown(string businessUnitCd, string facilityCd)
    {
        IEnumerable<SelectListItem> processListItems = new List<SelectListItem>();
        SQLPersistor p = new SQLPersistor(EADConnString);

        List<ProcessShown> processes = p.GetProcessShown(businessUnitCd, facilityCd);

        ProcessShown defaultProcessShown = new ProcessShown();
        defaultProcessShown.ProcessCd = string.Empty;
        defaultProcessShown.ProcessDesc = "Select Process...";

        processes.Insert(0, defaultProcessShown);

        processListItems = (from pr in processes
                             select new SelectListItem
                             {
                                 Text = pr.ProcessDesc,
                                 Value = pr.ProcessCd
                             });

        return Json(processListItems, JsonRequestBehavior.AllowGet);
    }

my SQLPersistor :我的 SQLPersistor :

 public List<ProcessShown> GetProcessShown(string businessUnitCd, string facilityCd)
    {
        List<ProcessShown> Processes = new List<ProcessShown>();

        if (businessUnitCd != string.Empty && facilityCd != string.Empty)
        {
            using (SqlConnection cnn = new SqlConnection(connString))
            {
                cnn.Open();

                string sql = "[Environmental].[GetProcessShown]";


                using (SqlCommand cmd = new SqlCommand(sql, cnn))
                {
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.Parameters.Add("@BUSUNIT", SqlDbType.VarChar).Value = businessUnitCd;
                    cmd.Parameters.Add("@FAC_CD", SqlDbType.VarChar).Value = facilityCd;
                    SqlDataReader dr = cmd.ExecuteReader();

                    using (DataTable dt = new DataTable())
                    {
                        dt.Load(dr);

                        foreach (DataRow row in dt.Rows)
                        {
                            ProcessShown ps = new ProcessShown(row["PROCESS_CD"].ToString(), !Convert.IsDBNull(row["PROCESS_NAME"]) ? row["PROCESS_NAME"].ToString() : string.Empty);

                            Processes.Add(ps);
                        }
                    }
                }
            }
        }

        return Processes;
    }

My jquery:我的jQuery:

 $("#Facility").change(function () {
    $("#ProcessShown").empty();
    $("#Aspects").empty();
    $("#AspectsCategory").empty();
    $("#Activity").empty();
    //document.getElementById("OnCallContactMessage").style.display = "none";

    // Incase theyve double clicked a cause and changed their mind
    document.getElementById("BusinessUnit").required = true;
    document.getElementById("Facility").required = true;
    document.getElementById("ProcessShown").required = true;
    document.getElementById("Aspects").required = true;
    document.getElementById("AspectCategoryDiv").required = true;
    document.getElementById("ActivityName").required = true;

    var ProcessOptions = {};
    ProcessOptions.url = $("ProcessDiv").data('url');
    ProcessOptions.type = "POST";
    ProcessOptions.data = JSON.stringify({ businessUnitCd: $("#BusinessUnit").val(), facilityCd: $("#Facility").val() });
    ProcessOptions.datatype = "json";
    ProcessOptions.contentType = "application/json";
    ProcessOptions.success = function (processes) {
        if (processes.length > 0) {
            for (var i = 0; i < processes.length; i++) {
                $("#ProcessShown").append(new Option(processes[i].Text, processes[i].Value));
            }
        }
    };
    ProcessOptions.error = function () { alert("Error occurred while getting Processes.") };
    $.ajax(ProcessOptions);
});

My view:我的看法:

                @* Processes Shown - Dropdown *@
            <div class="row" style="padding-top:10px">
                <div class="col-xs-3" style="padding-top:8px">
                    @Html.LabelFor(model => model.ProcessShown, new { @class = "group-label" })
                </div>
                <div class="col-xs-8" id="ProcessDiv" data-url="@Url.Action("GetProcessShown", "Aspects")">
                    @Html.DropDownListFor(model => model.ProcessShown, Model.ProcessList, new { @class = "form-control req-field", @required = "required" })
                </div>
            </div>

My stored procedure:我的存储过程:

ALTER PROCEDURE [Environmental].[GetProcessShown]
@FAC_CD VarChar(255),
@BUSUNIT VarChar(255)
AS
BEGIN
    SET NOCOUNT ON;

    SELECT CDTBL_PROCESSES.PROCESS_CD, PROCESS_NAME
    FROM(SELECT DISTINCT PROCESS_CD FROM ENVIRN_BU_PROCESS_FAC WHERE FAC_CD = @FAC_CD AND BUS_UNIT_CD = @BUSUNIT) PROCESSES 
    JOIN CDTBL_PROCESSES
    ON CDTBL_PROCESSES.PROCESS_CD = PROCESSES.PROCESS_CD 
    AND OBSLT_EST IS NULL
END

EDIT: If it helps, the error that shows when debugging is编辑:如果有帮助,调试时显示的错误是在此处输入图片说明

The order of parameters is important ,when you are using stored procedure使用stored procedure时,参数的顺序很重要

Your SP first parameter is @FAC_CD .您的 SP 第一个参数是@FAC_CD So you should change cmd.Parameters.Add order of parameters.所以你应该改变cmd.Parameters.Add参数的顺序。

like this像这样

cmd.Parameters.Add("@FAC_CD", SqlDbType.VarChar).Value = facilityCd;
cmd.Parameters.Add("@BUSUNIT", SqlDbType.VarChar).Value = businessUnitCd;

It most likely because of the way you pass the parameters in ajax.data section.这很可能是因为您在 ajax.data 部分中传递参数的方式。 There were many questions regarding this issue before.之前有很多关于这个问题的问题。 For a start you may see this link :首先,您可能会看到此链接:

Ajax Post Parameter is Always Null in MVC app MVC 应用程序中的 Ajax Post 参数始终为空

In short, try one of these :简而言之,请尝试以下方法之一:

  • don't use JSON.stringify .不要使用 JSON.stringify Just pass the data as is, OR只需按原样传递数据,或
  • construct the URL more or less like this : var targeturl = '@Url.Action("Test", "Controller")?id=' + ID;或多或少像这样构造 URL: var targeturl = '@Url.Action("Test", "Controller")?id=' + ID; , with GET method, OR , 使用 GET 方法,或
  • change the contentType to "application/x-www-form-urlencoded" , if you use POST method将 contentType 更改为"application/x-www-form-urlencoded" ,如果您使用 POST 方法

However, I've tried your original codes above and had no problem at all.但是,我已经尝试了上面的原始代码并且完全没有问题。

Hope it helps, anyway.无论如何,希望它有所帮助。

The data your are sending is actually a composite object and not two independent strings.您发送的数据实际上是一个复合对象,而不是两个独立的字符串。 You could match this by creating a model on the server side:您可以通过在服务器端创建模型来匹配它:

public class ProcessRequest
{
    public string Facility { get; set; }
    public string BusinessUnit { get; set; }
}

The controller method signature changes accordingly and must have an HttpPost attribute added since you are sending the HTTP request via POST.控制器方法签名会相应更改,并且必须添加 HttpPost 属性,因为您通过 POST 发送 HTTP 请求。

[HttpPost]
public JsonResult GetProcessShown(ProcessRequest requestData) {}

As for the Sql exception, the error is triggered when a NULL value is passed in as a parameter in the stored procedure.至于Sql异常,在存储过程中传入NULL值作为参数时会触发该错误。

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

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