ASP.NET MVC Ajax - InvalidOperationException,序列不包含任何元素

时间:2014-05-08 08:35:02

标签: jquery ajax asp.net-mvc linq invalidoperationexception

每当我对某个方法进行Ajax调用时,它会给出一个带有“sequence contains no elements”消息的InvalidOperationException,这很明显,因为我想验证它在输入不存在的文章时是否出错。

调用方法的Ajax

$.ajax({
    url: '@Url.Action("GetArticleName", "Date")',
    data: JSON.stringify({ barcode: $("#ArticleBarcode").val() }),

    type: 'POST',
    contentType: 'application/json; charset=utf-8',

    dataType: 'json',
    success: function (result) {
        var divInsert = document.getElementById("ArticleName");
        divInsert.innerHTML = result;
        validArticle = true;
    },

    error: function (xhr, s, error) {
        if (xhr.status == 404) {
            var divInsert = document.getElementById("ArticleName");
            divInsert.innerHTML = "Varen blev ikke fundet";
        }
        else {
            alert("error: " + s);
        }
        validArticle = false;
    }
});

返回错误的方法

[HttpPost]
public ActionResult GetArticleName(long barcode)
{
    ArticleDbContext artdb = new ArticleDbContext();
    String article = (String)(from art in artdb.Articles where art.Barcode == barcode select art.Name).SingleOrDefault();
    if (article == null)
    {
        return HttpNotFound();
    }
    return Json(article);
}

堆栈跟踪

[InvalidOperationException: Sekvensen indeholder ingen elementer] 
System.Linq.Enumerable.First(IEnumerable`1 source) +269
System.Data.Objects.ELinq.ObjectQueryProvider.<GetElementFunction>b__0(IEnumerable`1 sequence) +40
System.Data.Objects.ELinq.ObjectQueryProvider.ExecuteSingle(IEnumerable`1 query, Expression queryRoot) +59
System.Data.Objects.ELinq.ObjectQueryProvider.System.Linq.IQueryProvider.Execute(Expression expression) +133
System.Data.Entity.Internal.Linq.DbQueryProvider.Execute(Expression expression) +123
System.Linq.Queryable.First(IQueryable`1 source) +251
DatoCheckerMvc.Controllers.DateController.GetArticleName(Int64 barcode) in c:\Users\frederik\Documents\Visual Studio 2012\Projects\DatoCheckerMvc\DatoCheckerMvc\Controllers\DateController.cs:66   lambda_method(Closure , ControllerBase , Object[] ) +165
System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters) +14
System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters) +208
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +27
System.Web.Mvc.Async.<>c__DisplayClass42.<BeginInvokeSynchronousActionMethod>b__41() +28
System.Web.Mvc.Async.<>c__DisplayClass8`1.<BeginSynchronous>b__7(IAsyncResult _) +10
System.Web.Mvc.Async.WrappedAsyncResult`1.End() +57
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult) +48
System.Web.Mvc.Async.<>c__DisplayClass39.<BeginInvokeActionMethodWithFilters>b__33() +57
System.Web.Mvc.Async.<>c__DisplayClass4f.<InvokeActionMethodFilterAsynchronously>b__49() +223
System.Web.Mvc.Async.<>c__DisplayClass37.<BeginInvokeActionMethodWithFilters>b__36(IAsyncResult asyncResult) +10
System.Web.Mvc.Async.WrappedAsyncResult`1.End() +57
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethodWithFilters(IAsyncResult asyncResult) +48
System.Web.Mvc.Async.<>c__DisplayClass2a.<BeginInvokeAction>b__20() +24
System.Web.Mvc.Async.<>c__DisplayClass25.<BeginInvokeAction>b__22(IAsyncResult asyncResult) +102
System.Web.Mvc.Async.WrappedAsyncResult`1.End() +57
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult) +43
System.Web.Mvc.<>c__DisplayClass1d.<BeginExecuteCore>b__18(IAsyncResult asyncResult) +14
System.Web.Mvc.Async.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar) +23
System.Web.Mvc.Async.WrappedAsyncResult`1.End() +62
System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +57
System.Web.Mvc.Async.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar) +23
System.Web.Mvc.Async.WrappedAsyncResult`1.End() +62
System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +47
System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute(IAsyncResult asyncResult) +10
System.Web.Mvc.<>c__DisplayClass8.<BeginProcessRequest>b__3(IAsyncResult asyncResult) +25
System.Web.Mvc.Async.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar) +23
System.Web.Mvc.Async.WrappedAsyncResult`1.End() +62
System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +47
System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +9
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +9690172
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155

我试图在Linq查询的行中插入一个断点,但它似乎已经在方法名称的方法上抛出它。

有什么问题?

2 个答案:

答案 0 :(得分:1)

将您的查询更改为:

var article = from art in artdb.Articles where art.Barcode == barcode select art;

var firstUser = article .SingleOrDefault();

var firstUser = article .FirstOrDefault();

答案 1 :(得分:0)

您需要使用FirstOrDefault(),因为可能存在多个对象。

这样做:

var result = (from art in artdb.Articles 
              where art.Barcode == barcode 
              select art).FirstOrDefault();

string Name = result.Name;

你也可以这样做:

 var result = artdb.Articles.FirstOrDefault(art=>art.Barcode == barcode);

但如果只返回一个对象,则使用SingleOrDefault()

 var result = artdb.Articles.SingleOrDefault(art=>art.Barcode == barcode);