1
<select id="DdlModule" class="form-control input-sm "> </select>

Jquery Code to BInd Ddl Module

$.ajax({
    type: "POST",
    contentType: "application/json; charset=utf-8",
    url: "/Job/GetModules",
    data: "{}",
    dataType: "json",
    success: function (Result) {
            $("#DdlModule").append("<option value='0'>---Select---</option>");
            $.each(Result.d, function (key, value) {
                $("#ddlmodule").append($("<option></option>").val(value.modId).html(value.modName));
            });
    },
    error: function (Result) {
        alert("Error");
    }
});

Here is my Controller Action

public JsonResult GetModules()
{
    var Query = "EXEC [dbo].[Usp_ComboBind] @TableName='Module'";
    List<Usp_ComboBind_Module> objModule = objDbContext.Database.SqlQuery<Usp_ComboBind_Module>(Query).ToList();
    return Json(objModule, JsonRequestBehavior.AllowGet);
}

Error

Error:jquery-1.10.2.min.js:21 Uncaught TypeError: Cannot read property 'length' of undefined

4
  • Not related, but delete the pointless contentType and data attributes, and there is no need for JsonRequestBehavior.AllowGet if your making a POST Commented Aug 16, 2018 at 7:58
  • ok.thank you ,But Error is not solved yet Commented Aug 16, 2018 at 7:59
  • Use $.each(Result, function (key, value) { (not Result.d) Commented Aug 16, 2018 at 8:11
  • thank you code works after changed to Result Instead of Result.d Commented Aug 16, 2018 at 11:03

1 Answer 1

1

Since you're using type: "POST" in AJAX callback, make sure that HttpPostAttribute attribute included in controller action method like this:

[HttpPost]
public JsonResult GetModules()
{
    var Query = "EXEC [dbo].[Usp_ComboBind] @TableName='Module'";
    List<Usp_ComboBind_Module> objModule = objDbContext.Database.SqlQuery<Usp_ComboBind_Module>(Query).ToList();
    return Json(objModule);
}

And then put a check against undefined inside success result before iterating Result function parameter:

success: function (Result) {
    if (typeof Result !== 'undefined' && Result != undefined) {
        $("#DdlModule").append("<option value='0'>---Select---</option>");
        $.each(Result, function (key, value) {
            $("#ddlmodule").append($("<option></option>").val(value.modId).html(value.modName));
        });
    }
},

Note: Cannot read property 'length' of undefined occurs because you're trying to iterate an object which has undefined value, since $.each expects an array or collection object.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.