asp.net MVC練手 出錯及解決全過程
1.在Models文件中新建類Person.cs
public class Person
{
public string Name { get; set; }
public string Email { get; set; }
public string Phone { get; set; }
public bool? Gender { get; set; }
}
2.新建立一個文件夾名字叫 Action, 裏面添加一個頁面PersonIndex.cshtml
@using (Html.BeginForm("SendInformation", "Home"))//(actionName,controllerName)
{
<p>Your Name:@Html.TextBoxFor(x=>x.Name)</p>
<p>Your Email:@Html.TextBoxFor(x => x.Email)</p>
<p>Your Phone:@Html.TextBoxFor(x => x.Phone)</p>
<p>
Gender:
@Html.DropDownListFor(x=>x.Gender,
new[] { new SelectListItem(){ Text="I am a boy",Selected=true ,Value ="male"},
new SelectListItem () {Text="I am a girl",Selected =false ,Value ="female" }
},"please select your gender"
)
</p>
<p>
<input type="submit" value="Submit your information" />
</p>
}
3.添加超鏈接到Home 的Index.cshtml頁面
@Html.ActionLink("個人信息", "PersonInformation", "Home", routeValues:null,htmlAttributes:new {id="personIndexLink" })
4.在Controller的HomeController.cs中新增方法:
public string SendInformation(Person person)
{
return "Thank you," + person.Name;
}
public ActionResult PersonInformation()
{
return View("PersonIndex");
}
一切就緒,運行index.cdhtml頁面,點擊“個人信息”超鏈接,保存如下:
“/”應用程序中的服務器錯誤。
未找到視圖“PersonIndex”或其母版視圖,或沒有視圖引擎支持搜索的位置。搜索了以下位置:
~/Views/Home/PersonIndex.aspx
~/Views/Home/PersonIndex.ascx
~/Views/Shared/PersonIndex.aspx
~/Views/Shared/PersonIndex.ascx
~/Views/Home/PersonIndex.cshtml
~/Views/Home/PersonIndex.vbhtml
~/Views/Shared/PersonIndex.cshtml
~/Views/Shared/PersonIndex.vbhtml
不搜索我的視圖中的Action文件夾,根本就找不到PersonIndex.cshtml.修改方案往下看:
方案一:將PersonIndex.cshtml頁面挪到Home文件夾中
方案二:
1,第一步沒錯,保留
2,第二步,將視圖中PersonIndex.cshtml所在文件夾改爲PersonAction
@using (Html.BeginForm("SendInformation", "PersonAction"))//(actionName,controllerName)
{
<p>Your Name:@Html.TextBoxFor(x=>x.Name)</p>
<p>Your Email:@Html.TextBoxFor(x => x.Email)</p>
<p>Your Phone:@Html.TextBoxFor(x => x.Phone)</p>
<p>
Gender:
@Html.DropDownListFor(x=>x.Gender,
new[] { new SelectListItem(){ Text="I am a boy",Selected=true ,Value ="male"},
new SelectListItem () {Text="I am a girl",Selected =false ,Value ="female" }
},"please select your gender"
)
</p>
<p>
<input type="submit" value="Submit your information" />
</p>
}
3,第三步,@Html.ActionLink("個人信息", "PersonInformation", "PersonAction", routeValues:null,htmlAttributes:new {id="personIndexLink" })
4,第四步,在Controller文件中新增PersonActionController.cs,將上面第四步的代碼挪過來,結構如下:
其實就是遵循一個原則,名字相同。
方案一 是名字都爲Home,方案二是都爲PersonAction,我是初學者,原理我還不太懂。
哪位大哥大姐願意指教,這裏不勝感激!!!