【问题标题】:Couldn't Load the data on Dropdown menu using Asp.net Mvc Json无法使用 Asp.net Mvc Json 在下拉菜单上加载数据
【发布时间】:2019-07-04 17:00:41
【问题描述】:

我正在使用 Asp.net Mvc Json 创建一个简单的库存控制系统。当我试图加载类别数据时。类别数据未加载到下拉菜单中。到目前为止我尝试过的代码连同屏幕截图一起附在下面。 enter image description here

表单设计

<div class="card-action">
    <div class="form-group">
        <label class="form-label">Category</label>
        <select class="form-control" id="category" name="category"
                            placeholder="Category" required>
            <option value="">Please Select</option>
        </select>
    </div>
    </div>

jQuery

getCategory();

function getCategory() {
    $.ajax({
        type: 'GET',
        url: '/product/Getcategory',
        dataType: 'JSON',
        success: function (data) {

            console.log(data);
            for (var i = 0; i < data.length; i++) {
                $('#category').append($("<option/>", {
                    value: data[i].id,
                    text: data[i].cat_name,
                }));
            }

        },
        error: function (xhr, status, error) {
            alert(xhr.responseText);

        }

    });  
}

控制器

public class ProductController : Controller
{

    aspoEntities db = new aspoEntities();
    // GET: /Product/
    public ActionResult Index()
    {
        return View();
    }

    public ActionResult Getcategory()
    {
        using (aspoEntities db = new aspoEntities())
        {
            var category = db.categories.ToList();
            return Json(new { data = category }, JsonRequestBehavior.AllowGet);
        }
    }

}

【问题讨论】:

  • 您遇到的错误是什么?,console.log(data) 的值是什么也看看这个答案stackoverflow.com/questions/56537153/…
  • 加载资源失败:服务器响应状态为 500(内部服务器错误):58840/product/Getcategory:1 这是控制台上显示的错误
  • 在方法顶部添加[HttpGet] Getcategory
  • 仍然显示同样的错误,先生

标签: asp.net-mvc


【解决方案1】:

将您的控制器更改为

public class ProductController : Controller
{
    // GET: /Product/
    public ActionResult Index()
    {
        return View();
    }

    public ActionResult Getcategory()
    {
        aspoEntities db = new aspoEntities()
        var category = db.categories.ToList();

        return Json(category, JsonRequestBehavior.AllowGet);
    }

}

【讨论】:

  • 我会将我的项目通过电子邮件发送给您,先生
【解决方案2】:

您的数据库上下文似乎在 json 被序列化之前已被释放。

尝试将 db 上下文注入您的控制器并摆脱 using 语句。

或者将你的 return 语句移到 using 块之外。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-06-23
    • 2014-09-20
    • 2018-04-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多