将文本框字符串值保存到数据库c#中

本文关键字:数据库 保存 文本 字符串 | 更新日期: 2023-09-27 17:58:06

我有一个文本框,用户可以在其中输入他们想要的用户名并保存它。一旦他们保存了它,并且碰巧重新访问了他们的配置文件页面,该文本框应该填充他们保存的最后一个用户名以显示,用户仍然可以更改它并重新保存。我对这件事还很陌生,不知道如何正确地开始。我使用的是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

将文本框字符串值保存到数据库c#中

看起来您正试图将控制器操作的部分视图作为更大视图的一部分来呈现。在这种情况下,部分视图应该在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" />
}

_StudentName局部视图

@model School.Models.StudentNameModel
<fieldset>
    <ol>
        <li>
            @Html.LabelFor(m => m.StudentName)
            @Html.TextBoxFor(m=>m.StudentName)
        </li>
    </ol>
</fieldset>