我有一个用 C# 编写的 ASP.NET 应用程序。
我在 SQL Server 数据库中有一个表,其中包含两个字段:
Field1
Comments
我需要允许用户选择 Field1
并为该特定 Field1
添加注释
然后用户会将输入发送回服务器
我该如何实现这个目标?我可以使用哪个控件?已经有一个简单的 jquery 解决方案了吗?
最佳答案
我会将可能的选择放在下拉列表中,然后使用 jquery 发出 JSON 请求以从 Controller 获取数据,然后使用一个保存按钮调用另一个 javascript 函数将修改后的数据发布回 Controller 。
Controller :
public ActionResult GetFields()
{
var model=new MyModel();
model.Selections =(from m in database.table select m.Field1).ToList();
return View(model);
}
public ActionResult GetComments(string field1)
{
return Content((from c in database.table where(c.Field1==field1)select c.Comments).First());
}
[HttpPost]
public void SaveComments(string field1, string comments)
{
var record=(from r in database.table where(r.Field1==field1)select r).First();
record.Comments=comments;
database.SaveChanges;
return;
}
查看:
<script type="text/javascript>
function SaveComments(){
var url='@Url.Action("GetComments","YourControllerName");
url+='?field1='+$('#selections option:selected').text();
$('#selectedField').text($('#selections option:selected').text());
$('#commentEditor').load(url);
};
function SaveComments(){
var url='@Url.Action("SaveComments","YourControllerName")';
url+='?field1='+$('#selections option:selected').text()+'&comments='+$('#commentEditor').text();
$('#dummy').load(url);
};
</script>
<select id="selections" onchange="SelectionChanged()">
@foreach(var item in Model.Selections)
{
<option value="@item">@item</option>
}
</select>
<div id="selectedField"/>
<input type="text" id="commentEditor"/>
<input type="button" value="apply" onclick="SaveComments()"/>
<div id="dummy"/>
免责声明:这可能会出现一些小错误(通常不要在文本框中编写大块代码:P),您可能不应该使用虚拟 div,并且您需要在 View 模型上添加一个列出其 get 根据 Selections 中的值返回的列表。不过,这应该会给您一个总体思路。
关于c# - 同时选择和编辑数据的解决方案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7654434/