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

时间:2016-11-18 20:01:57

标签: c#

专家,

下拉列表是从数据库中挑选数据并在打开网页时保存相同的列并保存数据,其中保存在另一个而不是同名中,

<%@ 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 DISPLAY

1 个答案:

答案 0 :(得分:0)

为了更新数据库中的项目,我们首先需要确保我们知道需要引用哪一项。

首先,通过创建DropDownList,我们将要隐藏&#34; PlaceInfo&#34;的ID。我们正在展示。这将产生对&#34; SelectMethod&#34;的需求,以及一些其他调整:

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

DataTextField属性将显示在实际的DropDown中,DataValueField是一个隐藏属性,我们将使用它来引用ID,以便稍后调用该行。

SelectMethod(我有:GetMyPlaces)是我们用来填充DropDownList的方法。请原谅简洁,因为你可以通过多种方式做到这一点,但基本上你想要返回一个PlaceInfos列表:

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

最后 - 在btnSubmit_Click方法中,您希望使用下拉列表中隐藏的值字段来抓取我们要编辑的行:

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

为其分配新值,并告诉实体框架此模型现已修改:

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();
}

将更改保存到您的上下文中,您应该很高兴。