Sunday, April 28, 2013

Get the Primary key on Insert Using Entity Framework


Hey guys, this is just a quick code example to show how you can get the auto incrementing Primary Key ID when inserting a new row using Entity Framework.


 
All you need to do is insert the record as you normally would, then after you saveChanges() just assign the ID to an integer as seen below.
 int TaskID;  
 using (var context = new AppName.Data.Matters.MatterContext())  
 {  
   AppName.Data.Matters.Task task = new AppName.Data.Matters.Task();  
   task.TaskCategoryID = Int32.Parse(DrpDwnTaskCategory.SelectedValue);  
   task.CreatedByUserID = UserID;  
   task.DateCreated = DateTime.Now;  
   context.Task.Add(task);  
   context.SaveChanges();  
   TaskID = task.TaskID  
 }  

How easy is that!

Wednesday, April 10, 2013

ASP.NET Postback in jQuery UI Modal Dialog


Why is the postback not working?


When you use the jQuery UI Modal Dialog it pulls the referenced Div out of the form to create the Modal Dialog. As a result  ASP.Net elements such as the asp:Button and asp: TextBox will not function as they need to be in the form for your code behind to access them and the postback to work.

How do we fix it?


The easiest fix is to simply add the Div back to the form. In the code sample below, you will see that I have wired a function to the Open event of my ShowPannelInDialog method that appends the Div to the form.

Code:
<script type="text/javascript">
        function ShowPannelInDialog(PannelID, title) {
            $("#" + PannelID).dialog({
                title: title, 
                modal: true,
                open: function(type, data) { $(this).parent().appendTo("form");  },
                close: function (type, data) { ($(this).parent().replaceWith("")); }
        });
            return false;//prevent hyperlink from going to new page
        }
</script>

<div style="display:none" id="PopupBox">
Cost Name : <asp:TextBox ID="TxtDescription" runat="server"></asp:TextBox>
<asp:Button ID="BtnSubmit" runat="server" OnClick="BtnSubmit_Click" Text="Submit" />
</div>
<a onclick="showPannelInDialog('PopupBox','Title goes here');" href="#">Open Popup</a>

I have also wired a function to the Close event that removes the Div from the form. If you don’t do this then opening the Modal Dialog and closing it without submitting will create duplicates of your Div including the ASP.Net elements.


Did this post help you? Please let me know in the comments or use the buttons below to share it with your social network.