ASP.NET MVC Partial View基本使用
Model:
public class TestModel { [Required] public string Id { get; set; } }
Partial View(PartialInput.cshtml):
@model partialview.Models.TestModel @using (@Html.BeginForm("Index", "Test", FormMethod.Post, new { @id = "form1", @enctype = "multipart/form-data" })) { <div> @*使用ViewData传递数据*@ <h2>@ViewData["Name"]</h2> @Html.TextBoxFor(model => model.Id) <input type="submit" id="btn" value="Submit"> </div> }
Index View(Index.cshtml):
@{ ViewBag.Title = "Index"; } <body> @{ Html.RenderPartial("PartialInput"); } </body>
Read data from DB in Controller:
public class TestController : Controller { // GET: Test public ActionResult Index() { ViewData["Name"] = GetValue(2); return View(); } [HttpPost] public ActionResult Index(TestModel model) { ViewData["Name"] = GetValue(Convert.ToInt32(model.Id)); return View(); } public string GetValue(int id) { string connSQL = @"Data Source=(localdb)\ProjectsV13;Initial Catalog=master;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False"; using (SqlConnection conn = new SqlConnection(connSQL)) { string strSQL = "select name from PartialTest where id = " + id.ToString(); SqlCommand cmd = new SqlCommand(strSQL, conn); conn.Open(); if (cmd.ExecuteScalar() == null) { return "NULL"; } else { return cmd.ExecuteScalar().ToString(); } } } }
把圈子变小,把语言变干净,把成绩往上提,把故事往心里收,现在想要的以后你都会有。