您好我是C#的新手,可以与任何人的帮助,如何发现问题所在。我一直收到一条错误消息,指出在' _parcelService'行下检测到无法访问的代码在底部。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ABC.Data;
using ABC.Services;
using ABC.Services.Service;
namespace ABC.Controllers
{
public class AdminController : Controller
{
private ParcelService _parcelService;
public AdminController()
{
_parcelService = new ParcelService();
}
// GET: Admin
public ActionResult Index()
{
return View();
}
[HttpGet]
public ActionResult AddParcel()
{
return View();
}
[HttpPost]
public ActionResult AddParcel(ParcelDetail parcel)
{
return View();
{
_parcelService.AddParcel(parcel);
return RedirectToAction("Parcels",
new { TrackingID = parcel.TrackingID, controller = "Parcel" });
}
}
}
}
答案 0 :(得分:4)
在这一行,你已经从行动中返回了一个结果:
return View();
从函数返回的语句之后不能有任何内容。所以摆脱这条线:
[HttpPost]
public ActionResult AddParcel(ParcelDetail parcel)
{
_parcelService.AddParcel(parcel);
return RedirectToAction("Parcels",
new { TrackingID = parcel.TrackingID, controller = "Parcel" });
}
或者您可能想要应用一些逻辑,如果模型的验证失败,则会重新呈现相同的视图,否则会调用您的后端服务并重定向:
[HttpPost]
public ActionResult AddParcel(ParcelDetail parcel)
{
if (!ModelState.IsValid)
{
// The model that was passed to this action was not valid
// => Redisplay the same view so that the user can correct
// the errors
return View();
}
// At this stage we know that the model is valid and we can submit it
// for processing
_parcelService.AddParcel(parcel);
// redirect to a different action by returning the corresponding result
return RedirectToAction(
"Parcels",
new { TrackingID = parcel.TrackingID, controller = "Parcel" }
);
}
答案 1 :(得分:0)
你得到的错误是自我解释。以下
return View()
你返回一个视图。因此,此后的每个代码都无法访问。我认为您的代码的正确版本如下:
[HttpPost]
public ActionResult AddParcel(ParcelDetail parcel)
{
// Here you add the parcel
_parcelService.AddParcel(parcel);
// Then you make a redirect to a view that are visible all the parcels.
return RedirectToAction("Parcels",
new
{
TrackingID = parcel.TrackingID,
controller = "Parcel"
});
}
在你调用AddParcel
强制执行某些验证之前会很好,比如你的对象是否有效(检查Darin'n答案)。如果您的POST parcel
通过了这些验证,那么您应该致电AddParcel
。否则,您应该向客户返回她发布的错误对象并解释为什么这是错误的。
答案 2 :(得分:0)
return View(); // problem here
{
_parcelService.AddParcel(parcel);
return RedirectToAction("Parcels",
new { TrackingID = parcel.TrackingID, controller = "Parcel" });
}
这就是你的问题所在。在你的逻辑(代码)被击中之前你正在返回。你还有2个回报......
因为您有return RedirectToAction
,所以您可以删除return View()
所以解决方案:
[HttpPost]
public ActionResult AddParcel(ParcelDetail parcel)
{
// return View(); or just delete it.. since there is really no point to keep it commented out.
{
_parcelService.AddParcel(parcel);
return RedirectToAction("Parcels",
new { TrackingID = parcel.TrackingID, controller = "Parcel" });
}
}