Home > Back-end >  How to add value to existing object in ASP.NET
How to add value to existing object in ASP.NET

Time:11-09

I get a problem to add value to existing object in asp.net, I try to look for an example but always fail, when post the data from input form, just Name and City, but in controller I wanna add Address data (static data), please help me to solve this problem.

Create.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 : (in this controller I wanna add address value before pass to 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();
            }
        }
    }
}

Please help me and thank you.

CodePudding user response:

I would use a Viewmodel. This is a different class that allows you to map properties without allowing direct access to the data objects.

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; }
}

Now instead of using StudentModel on your View, use StudentViewmodel which exposes an Address property which you can add your address information to:

// 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();
    }
}

Remember to change the parameter type in the StudentDBHandle as well so that it also uses the StudentViewmodel object.

You don't even have to do extra mapping since the Viewmodel includes the same property names as your data model.

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;
}
  • Related