我在為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>
學生模型.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();
}
}
}
}
請幫助我,謝謝。
uj5u.com熱心網友回復:
我會使用一個視圖模型。這是一個不同的類,它允許您在不直接訪問資料物件的情況下映射屬性。
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;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/353657.html
上一篇:拆分字串值c#
下一篇:ASP.NET異步操作回傳型別
