【问题标题】:How to add value to existing object in ASP.NET如何为 ASP.NET 中的现有对象添加值
【发布时间】:2021-12-21 02:50:04
【问题描述】:

我在向 asp.net 中的现有对象添加值时遇到问题,我尝试查找示例但总是失败,当从输入表单发布数据时,只是名称和城市,但在控制器中我想添加地址数据(静态数据),请帮我解决这个问题。

创建.cshtml:

@model CRUDinMVC.Models.StudentModel


@using (Html.BeginForm()) 
{
    @Html.AntiForgeryToken()
    
<div class="form-horizontal">
    <h4>>@ViewBag.ItemList</h4>
    <hr />
    @Html.ValidationSummary(true, "", new { @class = "text-danger" })
    <div class="form-group">
        @Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.City, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.City, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.City, "", new { @class = "text-danger" })
        </div>
    </div>


    <div class="form-group">
        <div class="col-md-offset-2 col-md-10">
            <input type="submit" value="Create" class="btn btn-default" />
        </div>
    </div>
</div>
}

<div>
    @Html.ActionLink("Back to List", "Index")
</div>

<script src="~/Scripts/jquery-3.4.1.min.js"></script>
<script src="~/Scripts/jquery.validate.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>

StudentModel.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;

namespace CRUDinMVC.Models
{
    public class StudentModel
    {
        [Display(Name = "Id")]
        public int Id { get; set; }

        [Required(ErrorMessage = "First name is required.")]
        public string Name { get; set; }

        [Required(ErrorMessage = "City is required.")]
        public string City { get; set; }
    }
}

StudentDBHandle.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;

namespace CRUDinMVC.Models
{
public class StudentDBHandle
    {
private SqlConnection con;
        private void connection()
        {
            string constring = ConfigurationManager.ConnectionStrings["studentconn"].ToString();
            con = new SqlConnection(constring);
        }

        // **************** ADD NEW STUDENT *********************
        public bool AddStudent(StudentModel smodel)
        {
            connection();
            SqlCommand cmd = new SqlCommand("AddNewStudent", con);
            cmd.CommandType = CommandType.StoredProcedure;

            cmd.Parameters.AddWithValue("@Name", smodel.Name);
            cmd.Parameters.AddWithValue("@City", smodel.City);
            cmd.Parameters.AddWithValue("@Address", smodel.Address);

            con.Open();
            int i = cmd.ExecuteNonQuery();
            con.Close();

            if (i >= 1)
                return true;
            else
                return false;
        }
}
}

StudentController.cs :(在这个控制器中,我想在传递给 StudentDBHandle.cs 之前添加地址值)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;
using System.Web.Mvc;
using CRUDinMVC.Models;
using System.Diagnostics;

namespace CRUDinMVC.Controllers
{
    public class StudentController : Controller
    {
        // 1. *************RETRIEVE ALL STUDENT DETAILS ******************
        // GET: Student
        public ActionResult Index()
        {
            StudentDBHandle dbhandle = new StudentDBHandle();
            ModelState.Clear();
            return View(dbhandle.GetStudent());
        }

        // 2. *************ADD NEW STUDENT ******************
        // GET: Student/Create
        public ActionResult Create()
        {
            return View();
        }

        // POST: Student/Create
        [HttpPost]
        public ActionResult Create(StudentModel smodel) **// in this function I wanna add Address value, How to do it ?**
        {
            try
            {
                if (ModelState.IsValid)
                {
                    StudentDBHandle sdb = new StudentDBHandle(); 
                    if (sdb.AddStudent(smodel))
                    {
                        ViewBag.Message = "Student Details Added Successfully";
                        ModelState.Clear();
                    }
                }
                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }
    }
}

请帮助我,谢谢。

【问题讨论】:

    标签: asp.net asp.net-mvc


    【解决方案1】:

    我会使用 Viewmodel。这是一个不同的类,它允许您在不直接访问数据对象的情况下映射属性。

    public class StudentViewmodel
    {
        [Display(Name = "Id")]
        public int Id { get; set; }
    
        [Required(ErrorMessage = "First name is required.")]
        public string Name { get; set; }
    
        [Required(ErrorMessage = "City is required.")]
        public string City { get; set; }
    
        public string Address { get; set; }
    }
    

    现在不要在您的视图上使用StudentModel,而是使用StudentViewmodel,它公开了一个地址属性,您可以将您的地址信息添加到:

    // POST: Student/Create
    [HttpPost]
    public ActionResult Create(StudentViewmodel smodel)
    {
        try
        {
            if (ModelState.IsValid)
            {
                smodel.Address = "you put your address information here.";
                StudentDBHandle sdb = new StudentDBHandle();
                if (sdb.AddStudent(smodel))
                {
                    ViewBag.Message = "Student Details Added Successfully";
                    ModelState.Clear();
                }
            }
            return RedirectToAction("Index");
        }
        catch
        {
            return View();
        }
    }
    

    记得更改StudentDBHandle 中的参数类型,以便它也使用StudentViewmodel 对象。

    您甚至不必进行额外的映射,因为 Viewmodel 包含与您的数据模型相同的属性名称。

    public bool AddStudent(StudentViewmodel smodel)
    {
        connection();
        SqlCommand cmd = new SqlCommand("AddNewStudent", con);
        cmd.CommandType = CommandType.StoredProcedure;
    
        cmd.Parameters.AddWithValue("@Name", smodel.Name);
        cmd.Parameters.AddWithValue("@City", smodel.City);
        cmd.Parameters.AddWithValue("@Address", smodel.Address);
    
        con.Open();
        int i = cmd.ExecuteNonQuery();
        con.Close();
    
        // You can simplify your return, too.
        return i >= 1;
        //if (i >= 1)
        //  return true;
        //else
        //  return false;
    }
    

    【讨论】:

    • 哦,太棒了,谢谢@Ortund
    • 总是乐于提供帮助。如果您对它解决了问题感到满意,请不要忘记将答案标记为已接受!
    猜你喜欢
    • 1970-01-01
    • 2020-07-27
    • 2023-02-26
    • 2014-03-26
    • 1970-01-01
    • 2015-11-23
    • 2020-05-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多