It is pretty simple. Above the Gridview is a set of controls to define the criteria. There is boxes for City, State, and other controls that the user can fill out to get a list of Ranches. GetRanches() reads the criteria from the user, builds the LINQ query and pulls the list of Ranches.

    <asp:GridView runat="server" 
    ID="gvRanches" 
    DataKeyNames="RanchId" 
    ItemType="RanchManagementBusiness.Ranch"
    UpdateMethod="gvRanches_UpdateItem"
    OnRowCreated="gvRanches_RowCreated"
    SelectMethod="GetRanches"
    >
    <Columns>
        <asp:BoundField DataField="RanchCode" HeaderText="Code" />
        <asp:BoundField DataField="RanchName" HeaderText="Name" />
        <asp:TemplateField HeaderText="Billing Type"> 
            <ItemTemplate>
                <%#Item.RanchBillingType.BillingTypeName%>
            </ItemTemplate>
            <EditItemTemplate>
                <asp:DropDownList runat="server" ID="ddlBillingTypeEdit" SelectedValue='<%#Bind("RanchBillingTypeId") %>' />
            </EditItemTemplate>
        </asp:TemplateField>
        <asp:CommandField ShowEditButton="true"/>
    </Columns>
</asp:GridView>

Each Ranch has a Billing Type associated. The billing type has an ID (int) and description. So in gvRanches_RowCreated, I simply do this.

 protected void gvRanches_RowCreated(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowState == DataControlRowState.Edit)
    {
        var ddlBillingTypeEdit = (DropDownList)e.Row.FindControl("ddlBillingTypeEdit");
        var container = new RanchManagementModelContainer();
        var billingTypes = container.RanchBillingTypes.ToList();

        ddlBillingTypeEdit.DataValueField = "RanchBillingTypeId";
        ddlBillingTypeEdit.DataTextField = "BillingTypeName";
        ddlBillingTypeEdit.DataSource = billingTypes;
        ddlBillingTypeEdit.DataBind();
    }
}

And for the UpdateMethod

public void gvRanches_UpdateItem(int ranchId)
{
    var context = new RanchManagementModelContainer();
    var ranch = context.Ranches.Find(ranchId);
    TryUpdateModel(ranch);
    context.SaveChanges();
}

It does not like what I have in the Edit template ' />

I get the "Databinding methods such as Eval(), XPath(), and Bind() can only be used in the context of a databound control." error. It IS a databound control. GridView is databound control. What am I missing?

I am building an ASP.net MVC Web App with Local Authentication. I want to add some Web API endpoints, not for external use, but purely for use by jQuery AJAX calls on my own pages. So I added a Web API controller.

In order to integrate the authentication, I can do something like this:

[Authorize]
public IQueryable<object> GetLabels(int ModuleId)
{
    return db.Labels.Select(x => new { ID = x.ID, Name = x.Name, ModuleID = x.ModuleId }).Where(x => x.ModuleID == ModuleId );
}

This provides the desired behaviour. However, I encounter one problem: when accessing the API as a logged out user, it responds with the HTML response of the login page.

I would rather respond with a small JSON object giving an error or a 401 error. How can I change this behaviour?

I'm working with a jquery ui datepicker with asp.net mvc and when the web page open, it show the date with the time (2014/10/16 00:00:00) in the textbox for the datepicker, but if I select a date in the textbox for the datepicker, it will only show the date. I don't want to see the time, what's wrong?

Thanks!

The property in the model is set like this

[DataType(DataType.Date)]
[Required(ErrorMessageResourceType = typeof(Ressources.Resources), ErrorMessageResourceName="ErrorStartDateRequired")]
[Display(Name = "DateStarted", ResourceType = typeof(Ressources.Resources))]
public DateTime DateStarted { get; set; }

My date picker is set like this in my web page:

@section scripts{
<script language="javascript" type="text/javascript">
    $(document).ready(function () {
    var anchor = document.getElementById('@Model.Anchor');
    anchor.scrollIntoView(true);

    var d = new Date(@Model.Project.DateStarted.Year, @Model.Project.DateStarted.Month, @Model.Project.DateStarted.Day);
    $("#datePickerStartDate").datepicker({
        dateFormat: "yy/mm/dd",
        showOtherMonths: true,
        selectOtherMonths: true,
        showButtonPanel: true,
        changeMonth: true,
        changeYear: true,
        gotoCurrent: true,
        defaultDate: d
    });
});

}

and this is how the control is showed in the web page (cshtml)

<div class="form-group">
    @Html.LabelFor(model => model.Project.DateStarted, new { @class = "control-label col-md-2" })
    <div class="col-md-10">
        @Html.TextBoxFor(model => model.Project.DateStarted, new { id = "datePickerStartDate" })
        @Html.ValidationMessageFor(model => model.Project.DateStarted)
    </div>
</div>

I am contemplating creating a web application that will take the reading of scale (i.e. weight measurements) and insert them to a form field. I would like to make this as fluid a process as possible for a user. Suppose the scale is connected to the computer via a serial port so that the computer can communicate with the scale.

Any ideas on a good setup to achieve this? With a minimal number of clicks by the user? Ideally using a JavaScript ASP.NET setup.

I'm working on a project that involves using the header from another organization's website on my website. There's a search feature which, if possible, I need to work on my site (although it should just trigger the search on the org's website. That is, if they type "blah blah" into the input and click enter, then that should open http://www.organization_website.org/home/search-results.aspx?Search=blah+blah). Since I know nothing about ASP.NET, can someone, first of all, tell me whether what I'm trying to do is possible?

I'm trying to backtrack to see what I need to include in my code for this to work. When I hover my house over the search icon, it shows javascript:__doPostBack('dnn$dnnSEARCH$cmdSearch',''). So I searched for the function doPostBack(...) and found it:

var theForm = document.forms['Form'];
if (!theForm) {
    theForm = document.Form;
}
function __doPostBack(eventTarget, eventArgument) {
    if (!theForm.onsubmit || (theForm.onsubmit() != false)) {
        theForm.__EVENTTARGET.value = eventTarget;
        theForm.__EVENTARGUMENT.value = eventArgument;
        theForm.submit();
    }
}

In other words, searching takes a form with either id or name equal to Form, sets the value of a few of its inputs and then submits it. For some reason the action of the the form is set to be the page itself ....

<form method="post" action="/thispage.aspx" id="Form" enctype="multipart/form-data">

I don't really understand that. Anyways, I'm pretty much lost.

I want to use Web API in asp.net MVC application. Please suggest how can we define the architecture to handle this or if is there any effective solution available to this.

I am working on a .NET MVC web application that will contain a number of editable grids. Two features are required:

  1. Popup windows are used for editing.
  2. All changes are done in batch. That is, if an item is added/updated/deleted on the grid, it will not be sent to the server until the grid is told to save, then the changes are sent together.

We have been using the Telerik Kendo framework for our grids in the past, but unfortunately it does not support both of these things together. You can batch editing and popup editing, but not at the same time. Kendo has a semi-official workaround, but it's kind of unsatisfactory, especially for use on an iPad.

I have looked at a number of other libraries and haven't found one yet that can do both of these things together. MVC integration is very highly preferred. I'm looking over ParamQuery right now and haven't figure out yet whether it can or not, or whether it can do it in MVC if it can (some of these libraries have less features in the server-wrapped versions).

Any libraries that support both popup editing and batch submit these features together? It seems like it would be a pretty basic and common thing. If I can't find another library, I'll probably have to hack Kendo a little to make popup batch editing work.

I am trying to hide the Telerik RadGrid Edit column until the user clicks on the row the user wants to edit. Upon the click event I need the Edit hyperlink column to visible=True. I was hoping to set the column as visible=False by default, and then add a click event in my .cs page to alter the visibility property, but I cannot figure out how to target the edit column... Here is my code for the .aspx page.

<telerik:RadGrid ID="RG_POI" runat="server" OnPreRender="RG_POI_PreRender" OnItemDataBound="RG_POI_ItemDataBound" >
    <MasterTableView EditMode="InPlace" >
        <Columns>
            <telerik:GridEditCommandColumn Visible="false"/>
        </Columns>
        <EditFormSettings>
            <EditColumn FilterControlAltText="Filter EditCommandColumn1 column" UniqueName="EditCommandColumn1">
            </EditColumn>
        </EditFormSettings>
    </MasterTableView>

I dont have clear how to use Data-binding expressions correctly, I would like show/hide a column based on data from the table.

for example:

<asp:HyperLinkField DataNavigateUrlFields="ID" DataNavigateUrlFormatString="~/Insert_Inventario.aspx?ID={0}" 
Visible='<%= toogleInventario(Eval("Id")) %>' DataTextFormatString="{0}" NavigateUrl="~/Insert_Inventario.aspx"
                                Target="_top" Text="Inventario" />

In code behind :

 public string toogleInventario(string strID)
    {
        //do stuff
        return "True";
    }

but i get the error :

"Databinding expressions are only supported on objects that have a DataBinding event."

I know i can use the RowDataBound event for fix this, but i would like a more elegant way.

i have Created List View Control In Custom Web Control

following are my All Template :

    private class LayoutHeaderTemplate : ITemplate
    {
        public void InstantiateIn(Control container)
        {
            var div = new HtmlGenericControl("div") { ID = "itemPlaceholder" };

            var headerTable = new HtmlGenericControl("table");

            headerTable.Attributes.Add("border", "1px");
            var headerTr = new HtmlGenericControl("tr");
            var headerTd1 = new HtmlGenericControl("td");
            headerTd1.Attributes.Add("width", "200");
            headerTd1.Controls.Add(new CheckBox() { Text = "None", ID = "CheckNoneId", CssClass="CheckNone" });
            var headerTd2 = new HtmlGenericControl("td");
            headerTd2.Attributes.Add("width", "100");
            var headerTd3 = new HtmlGenericControl("td");
            headerTd3.Attributes.Add("width", "100");
            headerTr.Controls.Add(headerTd1);
            headerTr.Controls.Add(headerTd2);
            headerTr.Controls.Add(headerTd3);
            headerTable.Controls.Add(headerTr);
            container.Controls.Add(headerTable);

            container.Controls.Add(div);

            var footerTable = new HtmlGenericControl("table");
            footerTable.Attributes.Add("class", "Footer");
            footerTable.Attributes.Add("border", "1px");
            var footerTr = new HtmlGenericControl("tr");
            var footerTd1 = new HtmlGenericControl("td");
            footerTd1.Attributes.Add("width", "200");
            CheckBox CheckOther = new CheckBox() { Text = "Other", ID = "CheckOtherId", CssClass = "CheckOther" };
            CheckOther.Attributes.Add("onChange", "return otherCheckBoxSelect(this);");
            footerTd1.Controls.Add(CheckOther);                
            var footerTd2 = new HtmlGenericControl("td");
            footerTd2.Attributes.Add("colspan", "2");
            footerTd2.Attributes.Add("width", "205");
            footerTd2.Controls.Add(new CheckBox() { Text = "Show Additional Info", ID = "CheckAdditionalInfoId",CssClass="AdditionalInfo" });
            footerTr.Controls.Add(footerTd1);
            footerTr.Controls.Add(footerTd2);                
            footerTable.Controls.Add(footerTr);
            container.Controls.Add(footerTable);

        }

    }


    /// <summary>
    /// Created Item Template for List View.
    /// </summary>
    private class ItemTemplate : ITemplate
    {
        public void InstantiateIn(Control container)
        {
            var tbl1 = new HtmlGenericControl("table");
            tbl1.Attributes.Add("border", "1px");
            var tr1 = new HtmlGenericControl("tr");
            var td1 = new HtmlGenericControl("td");
            td1.Attributes.Add("width", "200");
            td1.DataBinding += DataBinding;
            var td2 = new HtmlGenericControl("td");
            td2.Attributes.Add("width", "100");
            td2.Controls.Add(new Button() { Text = "Edit", ID = "EditButtonId", CausesValidation = false, CommandName = "Edit" });
            var td3 = new HtmlGenericControl("td");
            td3.Attributes.Add("width", "100");
            td3.Controls.Add(new Button() { Text = "Delete", CausesValidation = false, CommandName = "Delete", OnClientClick = "return deleteConfirm();" });
            tr1.Controls.Add(td1);
            tr1.Controls.Add(td2);
            tr1.Controls.Add(td3);
            tbl1.Controls.Add(tr1);
            container.Controls.Add(tbl1);
        }

        public void DataBinding(object sender, EventArgs e)
        {
            var container = (HtmlGenericControl)sender;
            var dataItem = ((ListViewDataItem)container.NamingContainer).DataItem;
            container.Controls.Add(new Label() { Text = dataItem.ToString(), ID = "ItemLabelId" });

        }
    }

    /// <summary>
    /// Created EditItemTemplate for List View.
    /// </summary>
    private class EditItemTemplate : ITemplate
    {
        public void InstantiateIn(Control container)
        {
            var tbl1 = new HtmlGenericControl("table");
            tbl1.Attributes.Add("border", "1px");
            var tr1 = new HtmlGenericControl("tr");
            var td1 = new HtmlGenericControl("td");
            td1.Attributes.Add("width", "200");
            td1.DataBinding += DataBinding;
            var td2 = new HtmlGenericControl("td");
            td2.Attributes.Add("width", "100");
            td2.Controls.Add(new Button() { Text = "Update", ID = "UpdateButtonId", CausesValidation = false, CommandName = "Update" });
            var td3 = new HtmlGenericControl("td");
            td3.Attributes.Add("width", "100");
            td3.Controls.Add(new Button() { Text = "Cancel", ID = "CancelButtonId", CausesValidation = false, CommandName = "Cancel" });
            tr1.Controls.Add(td1);
            tr1.Controls.Add(td2);
            tr1.Controls.Add(td3);
            tbl1.Controls.Add(tr1);
            container.Controls.Add(tbl1);
        }

        public void DataBinding(object sender, EventArgs e)
        {
            var container = (HtmlGenericControl)sender;
            var dataItem = ((ListViewDataItem)container.NamingContainer).DataItem;
            container.Controls.Add(new TextBox() { Text = dataItem.ToString(), ID = "ItemTextBoxID" });

        }
    }`

following are my all List View Events:

protected void itemValueListView_ItemEditing(object sender, ListViewEditEventArgs e)

        {
            itemValueListView.EditIndex = e.NewEditIndex;

            this.itemValueListView.DataSource = this.ItemValueList;
            this.itemValueListView.DataBind();
        }

        protected void itemValueListView_ItemUpdating(object sender, ListViewUpdateEventArgs e)
        {
            ListViewItem item = itemValueListView.Items[e.ItemIndex];
            TextBox itemTextBox = (TextBox)item.FindControl("ItemTextBoxID");

            this.itemValueList.RemoveAt(e.ItemIndex);
            this.itemValueList.Insert(e.ItemIndex, itemTextBox.Text);

            itemValueListView.EditIndex = -1;
            this.itemValueListView.DataSource = this.ItemValueList;
            this.itemValueListView.DataBind();
        }

        protected void itemValueListView_ItemCanceling(object sender, ListViewCancelEventArgs e)
        {
            itemValueListView.EditIndex = -1;

            this.itemValueListView.DataSource = this.ItemValueList;
            this.itemValueListView.DataBind();
        }

        protected void itemValueListView_ItemDeleting(object sender, ListViewDeleteEventArgs e)
        {
            ListViewItem item = itemValueListView.Items[e.ItemIndex];

            Label itemLabel = (Label)item.FindControl("ItemLabelId");
            this.itemValueList.Remove(itemLabel.Text);

            this.itemValueListView.DataSource = this.ItemValueList;
            this.itemValueListView.DataBind();
        }`

when i am Clicking on update ,Delete button in ListView It is Giving Me error:

Server Error in '/' Application.

Invalid postback or callback argument.  Event validation is enabled using <pages enableEventValidation="true"/> in configuration or <%@ Page EnableEventValidation="true" %> in a page.  For security purposes, this feature verifies that arguments to postback or callback events originate from the server control that originally rendered them.  If the data is valid and expected, use the ClientScriptManager.RegisterForEventValidation method in order to register the postback or callback data for validation.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. 

Exception Details: System.ArgumentException: Invalid postback or callback argument.  Event validation is enabled using <pages enableEventValidation="true"/> in configuration or <%@ Page EnableEventValidation="true" %> in a page.  For security purposes, this feature verifies that arguments to postback or callback events originate from the server control that originally rendered them.  If the data is valid and expected, use the ClientScriptManager.RegisterForEventValidation method in order to register the postback or callback data for validation.

Source Error: 

An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.

Stack Trace: 


[ArgumentException: Invalid postback or callback argument.  Event validation is enabled using <pages enableEventValidation="true"/> in configuration or <%@ Page EnableEventValidation="true" %> in a page.  For security purposes, this feature verifies that arguments to postback or callback events originate from the server control that originally rendered them.  If the data is valid and expected, use the ClientScriptManager.RegisterForEventValidation method in order to register the postback or callback data for validation.]
   System.Web.UI.ClientScriptManager.ValidateEvent(String uniqueId, String argument) +144
   System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument) +122
   System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument) +10
   System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) +13
   System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData) +35
   System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +1724

Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.18446

Please Help Me I am Not able to get what is the exact problem.

I have piece of code:

    protected void Page_Load(object sender, EventArgs e)
    {
        _SearchResult.GridViewChanged += _SearchResult_GridViewChanged;
    }

    public Control GvControls { get; set; }

    protected void _SearchResult_GridViewChanged(object sender, Orders.GridViewChangedEventArgs e)
    {
        this.GvControls = e.GControl;            
    }

    protected void export_ServerClick()
    {
        new ExportGridView(this.GvControls,"report");
    }

One control generate a event with event arg and push a control by arg, then other (this) control do some push-ups with this arg

and when am i try to do push export_ServerClick() property GvControls equals null but before whould be not null. Why is it happening.

ThankX

I am trying to populate a grid with the DepositEntryObj it will not populate. I've been trying for two days and would appreciate any input anyone can give me. Please && Thank you!

This is my gridview:

 <asp:GridView runat="server" ID="grdvwDepositTransaction"
                AutoGenerateColumns="false" DataKeyNames="Status"
                OnRowCommand="grdvwDepositTransaction_RowCommand" OnRowDataBound="grd_RowDataBound"
                CssClass="grid" Width="1236px">
               <Columns>
                  <asp:BoundField DataField="DepositEntry.cardNumber" HeaderText="Card Number" ItemStyle-CssClass="mediumColumn columnCenter" />
                  <asp:BoundField DataField="DepositEntry.accountNumber" HeaderText="Account Number" ItemStyle-CssClass="mediumColumn columnCenter" />
                  <asp:BoundField DataField="DepositEntry.taxID" HeaderText="Tax ID" ItemStyle-CssClass="mediumColumn columnCenter" />
                  <asp:BoundField DataField="DepositEntry.firstName" HeaderText="Customer Name" ItemStyle-CssClass="mediumColumn columnCenter" />
                  <asp:BoundField DataField="DepositEntry.transactionDateTime" HeaderText="Transaction Date/Time" ItemStyle-CssClass="mediumColumn columnCenter" />
                  <asp:BoundField DataField="DepositEntry.cashAmount" HeaderText="Cash Amount" ItemStyle-CssClass="mediumColumn columnCenter" />
                  <asp:BoundField DataField="DepositEntry.depositAmount" HeaderText="Envelope Deposit Amount" ItemStyle-CssClass="mediumColumn columnCenter" />
               </Columns>
                    <EmptyDataTemplate>
                        <span style="font-weight: bold; text-anchor:middle;">No Transactions have been entered</span>
                    </EmptyDataTemplate>
            </asp:GridView>

I declared two objects:

    public DepositTransactionDE DepositTransactionObj;
    public DepositTransactionDE OriginalDepositTransactionObj;

Then in the page load I put:

        protected void Page_Load(object sender, EventArgs e)
       {
            try
            {
              if (!Page.IsPostBack)
              {
                  LoadDataGridDepositTransaction();
                  ScriptManager.RegisterStartupScript(this, GetType(), "Show HomeScreen", "ShowHomeScreen()", true);
              }
            }
            catch (Exception Ex)
            {
                Utility.LogError(Ex); 
            }

            if (ViewState["OriginalDepositTransactionObj"] == null)
            {
                OriginalDepositTransactionObj = new DepositTransactionDE();
                ViewState["OriginalDepositTransactionObj"] = OriginalDepositTransactionObj;
            }
            else
            {
                OriginalDepositTransactionObj = (DepositTransactionDE)ViewState["OriginalDepositTransactionObj"];
            }

            if (ViewState["DepositTransaction"] == null)
            {
                DepositTransactionObj = new DepositTransactionDE();
                ViewState["DepositTransaction"] = DepositTransactionObj;
            }
            else
            {
                DepositTransactionObj = (DepositTransactionDE)ViewState["DepositTransaction"];
            }

                OriginalDepositTransactionObj = (DepositTransactionDE)((Default)this.Page).OriginalDepositTransactionObj;
                DepositTransactionObj = (DepositTransactionDE)((Default)this.Page).DepositTransactionObj;


        }

I have a modal that adds input to the object:

        protected void btnAddModalTransaction_Click(object sender, EventArgs e)
        {
            DepositEntryDE DepositEntryObj = new DepositEntryDE();
            try
            {
                    DepositEntryObj.DepositEntry.cardNumber = TxtCardNumber.Text.ToString(); 
                    bool valid = DepositTransactionObj.validateDepositTransaction(DepositEntryObj, OriginalDepositTransactionObj);

            }
            catch (Exception Ex) { }
            LoadDataGridDepositTransaction();
        }

        private void LoadDataGridDepositTransaction()
        {

            grdvwDepositTransaction.DataSource = DepositTransactionObj.DepositEntryList;
            grdvwDepositTransaction.DataBind(); 

        }

These are the classes the objects are derived from:

   namespace ATMDepositTracking.DepositEntities
   {
     [Serializable]
     public class DepositEntryDE
    {
    private ATM_Cash_Deposit_Transactions _depositentry;
    private int _status;

    public DepositEntryDE()
    {
        _depositentry = new ATM_Cash_Deposit_Transactions();
        _status = 0;
    }

    public DepositEntryDE(ATM_Cash_Deposit_Transactions DepositEntryObj)
    {
        _depositentry = new ATM_Cash_Deposit_Transactions();
        _status = 0;
    }

    public ATM_Cash_Deposit_Transactions DepositEntry
    {
        get { return _depositentry; }
        set { _depositentry = value; }
    }

    public int Status
    {
        get { return _status; }
        set { _status = value; }
    }

}

}

    namespace ATMDepositTracking.DepositEntities
  {
       [Serializable]
   public class DepositTransactionDE
{

    private List<DepositEntryDE> _depositentryList = new List<DepositEntryDE>();



       public bool validateDepositTransaction(DepositEntryDE DepositEntryObj, DepositTransactionDE           DepositTransactionObj)
      {
               _depositentryList.Add(DepositEntryObj);
           return true;
      }

   public List<DepositEntryDE> DepositEntryList
    {
        get { return _depositentryList; }
        set { _depositentryList = value;}
    }
}

}

I am trying to divide two numbers and have it not round to the nearest whole number

    Dim dImgRatio As Decimal = 1.566
    Dim newWidth As Decimal = 400
    Dim newHeight As Decimal = newWidth \ dImgRatio

It always gives me newHeith = 200 instead of 255

It is like it is rounding the dImgRatio up to 2 before it does the division.

Any ideas?

I have 3 delete queries executed by my sql command. The last of the three queries can only execute if there is no reference to it in other tables. It fails to execute if there is a reference. So, if the last delete fails, I want to rollback to not lose the data that would be deleted in the previous 2 commands. This is why I need to use a SqlTransaction.

The following is what I was able to come up with. It in fact prevents the loss of any data, however, I am unable to delete anything and am always getting the popup (meaning every time it is executed, it is caught).

protected void editDelete(object sender, DirectEventArgs e)
{
    SqlConnection MyConnection = new SqlConnection();
    MyConnection.ConnectionString = ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;

    MyConnection.Open();

    // Start a local transaction.
    SqlTransaction sqlTran = MyConnection.BeginTransaction();

    try
    {
        SqlCommand MyCommand = new SqlCommand();
        MyCommand.CommandText = /* 3 queries removed to shorten code */;
        MyCommand.CommandType = CommandType.Text;
        MyCommand.Connection = MyConnection;

        SqlParameter p1 = new SqlParameter("@id", this.accountidEdit.Value);
        MyCommand.Parameters.Add(p1);

        MyCommand.ExecuteNonQuery();
        MyConnection.Close();


        /* reload and notification calls removed to shorten code */
    }
    catch (Exception)
    {
        sqlTran.Rollback();
        X.Msg.Alert("Error", "Error.").Show();
    }

}

In addition, I tried to find the problem by using:

catch (Exception sqlexception)
    {
        Console.WriteLine(sqlexception.Message);
        sqlTran.Rollback();
        X.Msg.Alert("Error", "Error.").Show();
    }

but nothing ever wrote to the console.. weird?

Is this the proper way to execute a SqlTransaction? I followed a guide from the microsoft site to do this. Why is it always being caught?

Thank you!

In a aspx page, source/markup mode, I can

Right-Click > View Code (F7)

This bring me to cs file, good. when I want to go back,

Right-Click > View Designer(Shift F7)

This bring me to aspx design mode which is very slow. I need source/markup mode.

My question is
how to use KeyBoard to make a real round trip?


Update: Thanks Ben. I followed your link, it works for me! I use VS 2012.

VS addin: View markup. Does exist something like that?

I have created two controllers for exporting type schemas and wadl and everything else is part of the api

So I created three routes, two for the special controllers (Schema and Wadl) and one for "everything else":

        config.Routes.MapHttpRoute(
            name: "Schemas",
            routeTemplate: "api/{controller}/{typeName}/{subType}",
            defaults: new { subtype = RouteParameter.Optional },
            constraints: new { controller = @"Schemas" }
        );

        config.Routes.MapHttpRoute(
            name: "Wadl",
            routeTemplate: "api/{controller}",
            defaults: null,
            constraints: new { controller = @"Wadl" }
        );

        config.Routes.MapHttpRoute(
            name: "api",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional },
            constraints: somethingsomethingsomething }
        );

I tried following this page: http://stephenwalther.com/archive/2008/08/07/asp-net-mvc-tip-30-create-custom-route-constraints

And created a variation on their NotEquals class:

public class NotEqual : IRouteConstraint
{
    private IEnumerable<string> Matches;

    public NotEqual(IEnumerable<string> matches)
    {
        Matches = matches;
    }

    public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
    {
        bool output = true;
        var name = values[parameterName].ToString();
        foreach (var match in Matches)
        {
            if (name.Contains(match))
            {
                output = false;
                break;
            }
        }
        return output;
    }
}

And changed the 3rd route to be:

        config.Routes.MapHttpRoute(
            name: "api",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional },
            constraints: new { controller = new NotEqual(new List<string> { "Schemas", "Wadl" }) }
        );

public class NotEqual : IRouteConstraint
{
    private IEnumerable<string> Matches;

    public NotEqual(IEnumerable<string> matches)
    {
        Matches = matches;
    }

    public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
    {
        bool output = true;
        var name = values[parameterName].ToString();
        foreach (var match in Matches)
        {
            if (name.Contains(match))
            {
                output = false;
                break;
            }
        }
        return output;
    }
}

Doesn't work, it still matches for all three controllers

It'll work fine with one route, but auto help page is ugly and misleading.

If I put a break on Match, it doesn't hit the break point.

The Regex constraints work perfectly, just the "everything else" one is not working

Why isn't that working?

I'm trying to do a post request on a page called Expression.cshtml with AngularJS:

$http.post('templates/Expression.cshtml', { data: $scope.elements[key]['expression'] });

It works well as you can see :

enter image description here

The problem is i can't get "data" parameter on Expression.cshtml , I have tried many things such as

@{

    dynamic expression = "";
    foreach (string name in Request.Form)
    {
    expression+=name;
    }
}
@expression

Or

@{

dynamic expression = "";
string expression = Request.Form["data"]    
}
@expression

And a lot of other things, but the problem is i've always an empty answer...

I need to make a dynamic table in asp.net MVC razor using Angularjs for my assignment. New column should be added on run time when user completely fill all the rows of 1st column. There is no limit of columns. On last entry row of each column, new column should be generated automatically.Here is the sample image

Time interval should be asked from user and new columns should be added according to the interval.

Thanks in advance.

I'm using Umbraco 7 and I want a partial view to render a left nav starting at a certain point up the tree where it finds a page with a certain property set.

I've tried this but it only works from a fixed depth 1 layer down in the tree. I want to do this from any depth within the site and have it recurse back up until it finds an item and have that be the root for the left nav.

@inherits Umbraco.Web.Mvc.UmbracoTemplatePage

@{
    @* Get the item above this one that has a property of resetLeftNav ticked *@
    var root = CurrentPage.AncestorOrSelf(1).Children.Where("resetLeftNav").First(); 
}

<ul class="nav left-nav">
    @foreach(var page in root.Children)
    {
        <li class="">
            <a href="@page.Url">@page.Name</a>
        </li>
    }
</ul>

I'm trying to create a HTML helper for displaying a dropdown box in a certain way.

I've started to create one like this:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Web;
using System.Web.Mvc;

namespace uQuiz.WebUI
{
    public static class HtmlHelpers
    {

        public static  MvcHtmlString TimerMinuteSelectBoxFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression)
        where TModel : class
        {
            // Error, no definition
            htmlHelper.DropDownBoxFor();
        }
    }
}

But htmlHelper doesn't contain a definition for DropDownBoxFor() or any other standard Html Helpers such as TextBoxFor()

Error 1 'System.Web.Mvc.HtmlHelper' does not contain a definition for 'DropDownBoxFor' and no extension method 'DropDownBoxFor' accepting a first argument of type 'System.Web.Mvc.HtmlHelper' could be found (are you missing a using directive or an assembly reference?)

I see that they are able to access it in this answer http://stackoverflow.com/a/16089427/894792 but I can't.

How can I get access to the standard HTML helpers in this answer.

I am using Razor Syntax. In my issue scenarion, I have a select dropdown, And when the user selects empName, a Pop Up opens. In this Popup I call a method with Razor which takes 2 parameters. the 2nd parameter is the empName(value selected in select dropdown).

How to pass this selected value as a 2nd parameter?

<select id="empName">
    <option value="">--Select--</option>
      <option>A</option>
      <option>B</option>
      <option>C</option>
</select

HTML of Pop Up Dialog, Which opens when User selects & clicks Open PopUp Btn.

<div>
    @foreach (var item in new obj.getMasterFields('Category', par2))
    {
         <label for="@item.Key">@item.Value</label> <br />
         ....
    }
</div>

Note : The Popup is Twitter Bootstrap Modal opened with Jquery.