您好我是cshtml的新手,我在ASP.NET Razor v2中有网页我想在点击按钮时将一些数据插入数据库。这些数据来自各种文本框,也可以上传图片。我可以知道如何在点击按钮时提供操作吗?
我在我的cshtml文件中尝试了这个:
<button type="submit" name="action" value="insertRegistered">Uložit</button>
@if (action == "insertRegistered")
{
var db1 = Database.Open("StarterSite");
var sql = "UPDATE services SET FileName=@0, FileContent=@1, MimeType=@2 WHERE IDservice=6";
db1.Execute(sql, fileName, fileContent, fileMime);
}
答案 0 :(得分:3)
在WebMatrix中,您可以通过以下方式实现此目的:
剃刀代码:
@{
var fileName = "";
var fileContent = "";
var fileMime = "";
var IDservice = "";
@*TEST CODE *@
@*if (!IsPost)
{
IDservice = "1";
var db = Database.Open("StarterSite");
var dbCommand = "SELECT * FROM services WHERE IDservice = @0";
var row = db.QuerySingle(dbCommand, IDservice);
fileContent = row.fileContent;
fileMime = row.MimeType;
fileName = row.fileName;
} *@
if (IsPost)
{
fileName = Request.Form["fileName"];
fileContent = Request.Form["fileContent"];
fileMime = Request.Form["fileMime"];
IDservice = Request.Form["IDservice"];
var db1 = Database.Open("StarterSite");
var sql = "UPDATE services SET FileName=@0, FileContent=@1, MimeType=@2 WHERE IDservice=@3";
db1.Execute(sql, fileName, fileContent, fileMime, IDservice);
}
}
标记应如下所示:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Service</title>
</head>
<body>
<form method="post">
<fieldset>
<legend>Service Information</legend>
<p><label for="fileName">FileName:</label>
<input type="text" name="fileName" value="@fileName" /></p>
<p><label for="fileContent">File Content:</label>
<input type="text" name="fileContent" value="@fileContent" /></p>
<p><label for="fileMime">Mime:</label>
<input type="text" name="fileMime" value="@fileMime" /></p>
<input type="hidden" name="IDservice" value="@IDservice" />
<p> <button type="submit" name="action" value="insert Registered">Uložit</button></p>
</fieldset>
</form>
</body>
</html>
这是一个有效的sample。
Here是一套教程,我相信它们应该非常有用!
答案 1 :(得分:1)
将数据库逻辑放入控制器操作中,如下所示:
public class HomeController : Controller
{
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Edit(int id, FormCollection collection)
{
try
{
// Do database update logic here
// Upon successfully updating the database redirect to a view
// that displays the information, read-only version not editable
return RedirectToAction("Index");
}
catch(Exception ex)
{
// If something went wrong, then re-display the view
// the user tried to update database from
return View();
}
}
}
现在,在您的视图中,使用HTML帮助器Html.BeginForm()
创建表单,如下所示:
@using (Html.BeginForm("ActionMethodName","ControllerName"))
{
... your input, labels, textboxes and other html controls go here
<input class="button" id="submit" type="submit" value="Uložit" />
}
注意:
Html.BeginForm()
将获取其中的所有内容,并将其作为表单数据提交给指定为参数的控制器操作。