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" })) {@*使用ViewData传递数据*@}@ViewData["Name"]
@Html.TextBoxFor(model => model.Id) "submit" id="btn" value="Submit">
Index View(Index.cshtml):
@{ ViewBag.Title = "Index"; } @{ Html.RenderPartial("PartialInput"); }
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(); } } } }