简体   繁体   English

将现有但已修改的实体附加到上下文(数据库中的下拉列表)

[英]Attaching an existing but modified entity to the context (Drop-down list from Database)

Experts, 专家们,

Drop-down list is picking data from database and saving against the same column upon opening the web page and save the data, where saving is happening in another instead of same name, 下拉列表是从数据库中选取数据,并在打开网页并保存数据时针对同一列进行保存,其中保存是使用另一个名称而不是相同名称进行的,

 <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %> <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title></title> <script src="http://ajax.aspnetcdn.com/ajax/jquery/jquery-1.9.0.js"></script> </head> <body> <form id="form1" runat="server"> <div class="form"> <p> <asp:Label ID="Label1" runat="server" Text="Place Name" AssociatedControlID="txtName"></asp:Label> <asp:DropDownList ID="txtName" runat="server" > </asp:DropDownList> </p> <p> <asp:Label ID="Label2" runat="server" Text="Address" AssociatedControlID="txtAddress"></asp:Label> <asp:TextBox ID="txtAddress" runat="server"></asp:TextBox> </p> <p> <asp:HiddenField ID="hdnLocation" runat="server" /> </p> <p> <asp:Button ID="btnSubmit" runat="server" Text="Save" OnClick="btnSubmit_Click" /> </p> <p id="message"></p> </div> </form> <script type="text/javascript"> if (navigator.geolocation) { navigator.geolocation.getCurrentPosition(showPosition, showError); } else { $("#message").html("Geolocation is not supported by this browser."); } function showPosition(position) { var latlondata = position.coords.latitude + "," + position.coords.longitude; var latlon = "Latitude" + position.coords.latitude + "," + "Longitude" + position.coords.longitude; $("#message").html(latlon); $("[id*=hdnLocation]").val(position.coords.longitude + " " + position.coords.latitude); } function showError(error) { if (error.code == 1) { $("#message").html("User denied the request for Geolocation."); } else if (error.code == 2) { $("#message").html("Location information is unavailable."); } else if (error.code == 3) { $("#message").html("The request to get user location timed out."); } else { $("#message").html("An unknown error occurred."); } } </script> </body> </html> 

 using System; using System.Collections.Generic; using System.Data.Entity.Spatial; using System.Linq; using System.Web; using System.Web.UI; using System.Data.SqlClient; using System.Web.UI.WebControls; using System.Data; using System.Configuration; using System.Web.Security; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; using System.Web.Configuration; public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (!this.IsPostBack) { string query = "SELECT PlaceID, Name,Address FROM Placeinfo"; string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString; using (SqlConnection con = new SqlConnection(constr)) { using (SqlCommand cmd = new SqlCommand(query)) { cmd.CommandType = CommandType.Text; cmd.Connection = con; con.Open(); using (SqlDataReader sdr = cmd.ExecuteReader()) { while (sdr.Read()) { ListItem item = new ListItem(); item.Text = sdr["Name"].ToString(); txtName.Items.Add(item); txtName.ClearSelection(); } } con.Close(); } } } } public List<PlaceInfo> GetMyPlaces() { return new SampleDBEntities().PlaceInfoes.ToList(); } protected void btnSubmit_Click(object sender, EventArgs e) { PlaceInfo placeToEdit = Context.placeinfoes.Find(Convert.ToInt32(txtName.DataValueField)); using (var context = new SampleDBEntities()) { PlaceInfo placeToUpdate = context.PlaceInfoes.Find(Convert.ToInt32(txtName.DataValueField)); placeToUpdate.Name = txtName.Text; placeToUpdate.Address = txtAddress.Text; placeToUpdate.Geolocation = DbGeography.FromText("POINT( " + hdnLocation.Value + ")"); context.Entry(placeToUpdate).State = System.Data.Entity.EntityState.Modified; context.SaveChanges(); } } } 

database DATABASE DISPLAY 数据库数据库显示

In order to update an item in a database, we first need to make sure we'll know which one we need to reference. 为了更新数据库中的一项,我们首先需要确保我们知道我们需要引用哪一项。

First, with the creation of your DropDownList, we'll want to hide the ID of the "PlaceInfo" we are displaying. 首先,随着您的DropDownList的创建,我们将要隐藏正在显示的“ PlaceInfo”的ID。 This will create the need for a "SelectMethod", and a few other adjustments: 这将需要“ SelectMethod”以及其他一些调整:

<asp:DropDownList ID="txtName" runat="server" ItemType="PlaceInfo" DataValueField="PlaceId" DataTextField="Name" SelectMethod="GetMyPlaces"></asp:DropDownList>

The DataTextField property is the one which will display in the actual DropDown, and the DataValueField is a hidden property which we will use to reference the ID so we can call that row later. DataTextField属性是将在实际的DropDown中显示的属性,而DataValueField是隐藏的属性,我们将使用该属性来引用ID,以便稍后可以调用该行。

The SelectMethod (I have as: GetMyPlaces) is the method we use to populate the DropDownList. SelectMethod(我的名字是:GetMyPlaces)是我们用来填充DropDownList的方法。 Please excuse the brevity, as you can do this a number of ways, but essentially you want to return a list of PlaceInfos: 为简便起见,请原谅,您可以通过多种方式进行此操作,但实际上您想返回一个PlaceInfos列表:

public List<PlaceInfo> GetMyPlaces()
{
    return new SampleDbEntities().PlaceInfoes.ToList();
}

Finally - in the btnSubmit_Click method, you want to grab the row we're going to edit by using the hidden Value field from the dropdown : 最后-在btnSubmit_Click方法中,您想使用下拉菜单中的隐藏值字段来获取我们要编辑的行:

PlaceInfo placeToEdit = Context.PlaceInfoes.Find(Convert.ToInt32(txtName.Value))

Assign it the new values, and tell entity framework this model is now modified: 为它分配新值,并告知实体框架此模型现已修改:

using (var context = new SampleDBEntities())
{
       PlaceInfo placeToUpdate = context.PlaceInfoes.Find(Convert.ToInt32(txtName.Value));
       placeToUpdate.Name = txtName.Text;
       placeToUpdate.Address = txtAddress.Text;
       placeToUpdate.Geolocation = DbGeography.FromText("POINT( "+hdnLocation.Value+")");

       context.Entry(placeToUpdate).State = EntityState.Modified;
       context.SaveChanges();
}

Save the changes to your context and you should be good to go. 将更改保存到您的上下文中,您应该会很好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM