![](/img/trans.png)
[英]C# Windows Form - How do I assign a double value to a combo box string to then be displayed in a text box?
[英]saving text box string value to database c#
我有一個文本框,用戶可以在其中輸入所需的用戶名並保存。 一旦他們保存它並碰巧重新訪問其個人資料頁面,該文本框應使用他們保存顯示的最后一個用戶名進行填充,用戶仍然可以更改並重新保存。 我對此並不陌生,不確定如何正確啟動它。 我正在使用vs 2012 asp.net MVC 4 C#。 到目前為止,這是我的代碼:
@model School.Models.StudentNameModel
@using (Html.BeginForm("_StudentNamePartial", "Profile")) {
@Html.AntiForgeryToken()
@Html.ValidationSummary()
<fieldset>
<ol>
<li>
@Html.LabelFor(m => m.StudentName)
@Html.DisplayFor(m => m.StudentName)
@Html.TextBoxFor(m=>m.StudentName)
<button type="button" value="save" />
</li>
</ol>
</fieldset>
}
這是我的模型:
public class StudentNameModel
{
[Display(Name = "Student Name")]
public string StudentName{ get; set; }
}
我的控制器:
GET-從數據庫中獲取學生姓名(如果存在)。
[HttpPost]
public ActionResult _StudentNamePartial(int id)
{
id = WebSecurity.CurrentStudentId;
var model = new StudentNameModel();
using (var db = new StudentsDataContext())
{
var result = (from u in db.Students
where u.ID == id
select u.StudentName).FirstOrDefault();
if(result != null)
model.StudentName= result;
}
return View(model);
}
POST-這是我要為學生保存新用戶名的地方
[HttpPost]
public ActionResult _StudentNamePartial(StudentNameModel model)
{
if (ModelState.IsValid)
{
using (var db = new StudentDataContext())
{
try
{
}
catch (Exception)
{
throw;
}
}
return RedirectToAction("ProfileAccount");
}
return View(model);
}
我也遇到麻煩,當我顯示用戶名時,它沒有命中我的Action
方法,並且它始終報告Object引用為null。 任何幫助都會很棒。 感謝:D
似乎您正在嘗試從控制器動作中呈現部分視圖,作為更大視圖的一部分。 在這種情況下,應在ProfileAccount
視圖中呈現部分視圖。
您可以像下面這樣構造控制器和視圖(粗略的輪廓):
ProfileAccount查看模型 :
public class ProfileAccountView
{
public StudentNameModel StudentName { get; set; }
}
配置文件控制器 :
[HttpGet]
public ActionResult ProfileAccount(int id)
{
// Get whatever info you need and store in a ViewModel
var model = new ProfileAccountView();
// Get the student info and store within ProfileAccountView
// Do your database reads
model.StudentName = new StudentNameModel { StudentName = result };
return View(model);
}
[HttpPost]
public ActionResult ProfileAccount(ProfileAccountView profile)
{
// Do whatever processing here
}
個人資料帳戶視圖
@model School.Models.ProfileAccountView
@using (Html.BeginForm("ProfileAccount", "Profile"))
{
@Html.RenderPartial('_StudentNamePartial', Model.StudentName);
<button type="button" value="save" />
}
_StudentNamePartial局部視圖
@model School.Models.StudentNameModel
<fieldset>
<ol>
<li>
@Html.LabelFor(m => m.StudentName)
@Html.TextBoxFor(m=>m.StudentName)
</li>
</ol>
</fieldset>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.