ObjectDataSource Insert arroja un error (usando objetos comerciales)
-
06-09-2019 - |
Pregunta
Vista rápida
- Intentando insertar un objeto comercial usando ObjectDataSource (en un GridView)
- Obtenga el siguiente error
ObjectDataSource 'ObjectDataSource1' no tiene valores para insertar.Compruebe que el diccionario de 'valores' contenga valores.
Configuración del proyecto
- Persona: objeto de negocio ficticio simple (nombre y edad)
- PersonBinder: contiene los métodos para el origen de datos del objeto (seleccionar e insertar en este caso)
- InsertGrid: Grid simple (hereda GridView) agrega un botón "Agregar" en el pie de página, que a su vez llama a Insertar de DataSource
- Predeterminado: página ASPX, contiene la cuadrícula y el origen de datos (aplica parámetros de inserción al DataSorce)
Tenga en cuenta que agregué comentarios TODO, lo que creo que son áreas clave
El código
Carpeta de personasFaltando a la persona (obtiene 2 propiedades) aquí está la carpeta
/// <summary>
/// A binding Class.
/// </summary>
public class PersonBinder
{
public IEnumerable<Person> Select()
{
List<Person> people = new List<Person>();
for (int i = 0; i < 9; i++)
{
Person person = new Person();
person.Name = "Name " + i.ToString();
person.Age = i;
people.Add(person);
}
return people;
}
public void Insert(Person p)
{
//TODO: the Insert Method
//errors before this.
}
}
Insertar cuadrícula
public class InsertGrid : GridView
{
protected override void OnInit(System.EventArgs e)
{
base.OnInit(e);
ShowFooter = true;
DataBind();
}
/// <summary>
/// here to handle button clicks.
/// </summary>
private void ModeCommand(object sender, CommandEventArgs e)
{
switch (e.CommandName)
{
case "Add":
//ObjectDataSource objectDataSource = DataSource as ObjectDataSource;
ObjectDataSource objectDataSource = Parent.FindControl(DataSourceID) as ObjectDataSource;
if (objectDataSource != null)
{
//TODO: Errors HERE!
objectDataSource.Insert();
}
break;
}
}
/// <summary>
/// Raises the <see cref="E:System.Web.UI.WebControls.GridView.RowDataBound"/> event.
/// </summary>
/// <param name="e">A <see cref="T:System.Web.UI.WebControls.GridViewRowEventArgs"/> that contains event data.</param>
protected override void OnRowDataBound(GridViewRowEventArgs e)
{
base.OnDataBound(e);
//add an insert button
if (e.Row.RowType == DataControlRowType.Footer)
{
ImageButton ibtnAdd = new ImageButton();
ibtnAdd.ID = "Add";
ibtnAdd.CommandName = "Add";
ibtnAdd.ToolTip = "Add new Item";
ibtnAdd.ImageAlign = ImageAlign.AbsMiddle;
ibtnAdd.Style.Add("cursor", "pointer");
ibtnAdd.CausesValidation = true;
ibtnAdd.Command += ModeCommand;
ibtnAdd.Enabled = true;
e.Row.Cells[0].Controls.Add(ibtnAdd);
}
}
}
HTML predeterminado
<form id="form1" runat="server">
<div>
<asp:ObjectDataSource ID="ObjectDataSource1" runat="server"
DataObjectTypeName="GridViewSample.Person" InsertMethod="Insert"
SelectMethod="Select" TypeName="GridViewSample.PersonBinder">
</asp:ObjectDataSource>
</div>
<br />
<cc1:InsertGrid ID="InsertGrid1" runat="server" AutoGenerateColumns="False"
DataSourceID="ObjectDataSource1">
<Columns>
<asp:BoundField DataField="Name" HeaderText="Name" SortExpression="Name" />
<asp:BoundField DataField="Age" HeaderText="Age" SortExpression="Age" />
</Columns>
</cc1:InsertGrid>
</form>
Código subyacente predeterminado
public partial class _Default : System.Web.UI.Page
{
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
//TODO: here is the insert PARAMs. what am i missing.
ObjectDataSource1.InsertParameters.Add("Name", "");
ObjectDataSource1.InsertParameters.Add("Age", "0");
}
protected void Page_Load(object sender, EventArgs e)
{
//TODO: Tried this too
IDataSource ds = ObjectDataSource1;
DataSourceView view = ds.GetView(InsertGrid1.DataMember);
Dictionary<string, string> values = new Dictionary<string, string>();
values.Add("Name", "");
//values.Add("Age", "0");
view.Insert(values, delegate { return false; });
}
}
Solución
La siguiente funciona realmente.
IDataSource ds = ObjectDataSource1;
DataSourceView view = ds.GetView(InsertGrid1.DataMember);
Dictionary<string, string> values = new Dictionary<string, string>();
values.Add("Name", "");
//values.Add("Age", "0");
view.Insert(values, delegate { return false; });
lo que tenía que hacer era eliminar / reemplazar el
//TODO: Errors HERE!
objectDataSource.Insert();
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow