错误在Create()函数
中创建()
错误1'MvcAnketaIT.Controllers.SurveyController.Create()':并非所有代码路径都返回值
代码
public ActionResult Create()
{
int myId = getIdByUser(this.User.Identity.Name);
if (this.User.Identity.IsAuthenticated)
{
if (myId == -1) //no questionnaire in db
{
SurveyModel survey = new SurveyModel();
ViewBag.userName = this.User.Identity.Name;
ViewBag.Q3Sex = new SelectList(db.Genders, "ID", "gender");
ViewBag.Q8Question1 = new SelectList(db.Questions1, "Id", "Technology");
ViewBag.Q9Question2_1 = new SelectList(db.Satisfaction, "ID", "Name");
ViewBag.Q10Question2_2 = new SelectList(db.Satisfaction, "ID", "Name");
ViewBag.Q11Question2_3 = new SelectList(db.Satisfaction, "ID", "Name");
ViewBag.Q12Question2_4 = new SelectList(db.Satisfaction, "ID", "Name");
ViewBag.Q13Question2_5 = new SelectList(db.Satisfaction, "ID", "Name");
ViewBag.Q14Question2_6 = new SelectList(db.Satisfaction, "ID", "Name");
ViewBag.Q15Question2_7 = new SelectList(db.Satisfaction, "ID", "Name");
ViewBag.Q16Question2_8 = new SelectList(db.Satisfaction, "ID", "Name");
ViewBag.Q17Question3 = new SelectList(db.Questions3, "ID", "Solve");
ViewBag.Q19Question5 = new SelectList(db.Questions5, "ID", "No_Contacts");
ViewBag.Q20Question6 = new SelectList(db.Questions6, "ID", "Recommendation");
return View();
}
}
else //user already has a questionnaire fulfilled
{
return RedirectToAction("Edit/" + myId); //redirect to the right id of the user
}
}
答案 0 :(得分:1)
您在if
块内声明了一个变量:
if (something)
{
int myId = getIdByUser(this.User.Identity.Name);
}
else
{
// myId doesn't exist here.
}
因此该变量只能在该块的范围内访问。要在更大的范围内使用它,需要在块之外声明它:
int myId;
if (something)
{
myId = getIdByUser(this.User.Identity.Name);
}
else
{
// myId is accessible here
// though runs the risk of not having been set to anything
// depending on whether or not the if condition was met
}
修改:您在问题中添加的内容是完全不同的问题。但消息很清楚。并非所有代码路径都返回值。你所拥有的结构可以简化为:
if (something)
{
if (something_else)
{
return;
}
}
else
{
return;
}
如果something
为真,会发生什么,但something_else
不是?没有达到return
语句。因此,该函数不返回任何内容。这会导致编译器错误。您需要在每个代码路径中从函数返回一些内容。在这种情况下,这里:
if (something)
{
if (something_else)
{
return;
}
// Need to return a value here
}
else
{
return;
}
答案 1 :(得分:1)
问题在于变量的范围 - 在IF块中声明了myID,并且您正尝试在ELSE块中使用它。
else块不知道这个变量,这是你得到的错误信息。
答案 2 :(得分:0)
myId必须在if块之外定义,就像在else中一样,你还没有声明它。请尝试使用此版本2:
public ActionResult Create()
{
int myId = getIdByUser(this.User.Identity.Name);
if (this.User.Identity.IsAuthenticated)
{
if (myId == -1) //no questionnaire in db
{
SurveyModel survey = new SurveyModel();
return View();
}
}
else //user already has a questionnaire fulfilled
{
//redirect to the right id of the user
return RedirectToAction("Edit/" + myId);
}
return View();
}