object with additional properties from json-like notation string should created. Method will called from Razor view to pass colmodel to jqgrid as json object like

@Html.Raw( Json.Encode( Model.GetColModel()))

Method should have signature like

object GetColModel(string colName, int colWidth, string additonalProperties)

For example,

GetColModel("customer", 17, "address=\"Toronto\", index=1555" )

should return object

new { colName="customer", colwidth=17, address="Toronto", index=1555 }

There may be nested properties like in JSON, eq.

GetColModel("customer", 17, "formatoptions= new { formatter=\"number\", editable=true } " )

should return object

new { colName="customer", colwidth=17, formatoptions=new {
                   formatter="number", 
                   editable=true
                   }
}

I tried method

    public object GetColModel(string colName, int colWidth, string additonalProperties)
    {
        return new
        {
            name = colName,
            width = colWidth,
            &addtitionalProperties
        };
    }

but this fails since macros are not supported in C#

How to create such method or other way to add properties from database to json strung in Razor view ?

It is called from ASP.NET/Mono C# MVC 4 viewmodel. Razor views and RazorEngine are used.

I'm developing an web application in ASP.NET MVC (Code First) and i'm new to Entity Framework, i'm having hard time understanding the relations.

I have 3 models named: Worker, Overhour and Accounting. I'm basically recording payments and salaries for employees. So, Worker can have multiple overhours (extra work time) and accounting records. Overhour should have only one worker, every overhour should have one accounting record too. Accounting should have one worker.

Here are my models:

Worker

    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int WorkerId { get; set; }
    public bool WorkerActive { get; set; }
    public string WorkerFullName { get; set; }
    public eWorkerType WorkerType { get; set; }
    public string WorkerJobDescription { get; set; }
    public DateTime WorkerStartDate { get; set; }
    public decimal WorkerSalary { get; set; }
    public decimal WorkerSalaryBankAmount { get; set; }
    public decimal WorkerOverWorkSalary { get; set; }
    public DateTime WorkerBirthDate { get; set; }
    public string WorkerAddress { get; set; }
    public string WorkerPhone1 { get; set; }
    public string WorkerPhone2 { get; set; }

    public virtual ICollection<Overhour> Overhours { get; set; }
    public virtual ICollection<Accounting> Accountings { get; set; }

Overhour

    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int OverhourId { get; set; }
    public int WorkerId { get; set; }
    public int PhaseId { get; set; }
    public int AccountingId { get; set; }
    public int OverhourAmount { get; set; }
    public DateTime OverhourDate { get; set; }
    public virtual Worker Worker { get; set; }
    public virtual Phase Phase { get; set; }
    public virtual Accounting Accounting { get; set; }

Accounting

    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int AccountingId { get; set; }
    public eAccountingType AccountingType { get; set; }
    public ePaymentMethod AccountingMethod { get; set; }
    public string AccountingNote { get; set; }
    public decimal AccountingBorc { get; set; }
    public decimal AccountingAlacak { get; set; }
    public int WorkerId { get; set; }
    public int PhaseId { get; set; }
    public virtual Worker Worker { get; set; }
    public virtual Phase Phase { get; set; }

There are few problems:

  1. I'm not sure if i created models right. I can save and get related data but like i said i'm not sure.
  2. When i try to add a relation between Overhour and Accounting it gives me an error like this:

Introducing FOREIGN KEY constraint 'FK_dbo.Overhours_dbo.Accountings_AccountingId' on table 'Overhours' may cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints.

What am i missing here?

Thanks

I am not able to run my web application on Microsoft Visual Studio Community 2015

when run project i am getting bellow error message

Error message

in ASP MVC RAZOR

I want to create a button that when clicked it will add a TextBoxFor and on postback i want to get the inputted value from the textboxes created.

Help is much appreciated :)

I'm working on a wedding website for myself so we can let our guests reserve items from our gift list (which are things we'll be doing on honeymoon) and give us a cheque on the day.

I have a DataList which is retrieving a table from my MSSQL and displaying it on my aspx page. One of the values stored in this table is a quantity.

What I want is the ability to populate a asp:DropDownList with the number of options from the Quantity field then click a button and this adds X of that item to the cart (cart is running fine with button for adding one option). Where I'm struggling is actually getting the dropdown populating. My current train of thought is to have a C# function add new items in a for loop based on the quantity.

Here is what I'm trying

aspx

<asp:DataList ID="DataList2" runat="server" DataKeyField="pKey"  DataSourceID="WeddingDatabase">
    <ItemTemplate>
        <div class="Gift"> 
            <!-- Other fields ignored for purpose of quesion -->                  
            Quantity:
            <asp:Label ID="QuantityLabel" runat="server" Text='<%# Eval("Quantity") %>' />
            <br />

            <asp:DropDownList ID="QuantityDropdown" runat="server" />
            <% FillDropdown((int)Eval("Quantity")); %>
            <br />

            <asp:Button ID="Btn" runat="server" Text="Add to Cart" CommandArgument='<%# Eval("pKey") %>' OnCommand="AddToCart" />
        </div>
    </ItemTemplate>
</asp:DataList>

<asp:SqlDataSource ID="SqlDataSource2" runat="server" 
ConnectionString="<%$ ConnectionStrings:DB_9EF896_weddingConnectionString %>" 
SelectCommand="SELECT * FROM [Giftlist] ORDER BY [Title] ASC"></asp:SqlDataSource>
<asp:SqlDataSource ID="SqlDataSource3" runat="server"></asp:SqlDataSource>

aspx.cs

    public void FillDropdown(int inQuantity)
    {
        DropDownList dropdown = this.FindControl("QuantityDropdown") as DropDownList;

        for (int i = 0; i < inQuantity; i++)
        {
            dropdown.Items.Add(new ListItem("" + (i+1)));
        }            
    }

Right now I'm struggling to even get it to compile. Whilst I know what I want to do it's the code that is getting the upper hand on me here.

Any help would be much appreciated!

I have followed the tutorial tutorial . I have read that the first file to be execute in my web app is startup.cs, but startup.cs contains only the following code. Which steps happened after the execution of this file? I don't see any page opening... Thank!

using Microsoft.Owin;
using Owin;

[assembly: OwinStartupAttribute(typeof(ContactManager.Startup))]
namespace ContactManager
{
    public partial class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            ConfigureAuth(app);
        }
    }
}

I have setup log4net as below, but it is not writing to the file. I have ran the application with a Breakpoint to check for Exceptions but NO exception is thrown. Please help Web.config

    <configSections>
    <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/>
  </configSections>
  <log4net>
    <appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender">
      <file value="C:\\Users\\yperez\\Desktop\\Demos\\AvatarPasswordReset\\mylogfile.txt" />
      <appendToFile value="true" />
      <rollingStyle value="Size" />
      <maxSizeRollBackups value="5" />
      <maximumFileSize value="10MB" />
      <staticLogFileName value="true" />
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%date [%thread] %level %logger - %message%newline" />
      </layout>
    </appender>
    <root>
      <level value="INFO" />
      <appender-ref ref="FileApender" />
    </root>
  </log4net>

Global.asax

<%@ Application Language="C#" %>

void Application_Start(object sender, EventArgs e) 
{
    log4net.Config.XmlConfigurator.Configure();

}
//More empty methods below

Default.aspx

using log4net;
//Other using statements
[assembly:log4net.Config.XmlConfigurator(Watch = true)]
public partial class _Default : System.Web.UI.Page{
//More code and methods...
  public void AppendToLog(string new_password, string user_named_changed, string sent)
{
    try
    {
        string date = DateTime.Now.ToString();
        string PCUser = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
        string a = String.Format("|{0}|{1}|{2}|{3}|{4}", date, PCUser, user_named_changed, new_password, sent);

        ILog logger = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
        logger.Info(a + "\r\n");
    }
    catch (Exception exc) { logger_status = exc.ToString(); }

}

I'm building a aspnet mvc6 application where I want to pass values from View to controller. My view has multiple buttons having IDs and I want to pass the ID of the button which is clicked to my controller using my viewmodel.

Controller:

public class HomeController : Controller
{
    private SampleDbContext _context;
    private HomeViewModel _viewmodel;

    public HomeController(SampleDbContext context, HomeViewModel model)
    {
        _viewmodel = model;
        _context = context;
    }

    public IActionResult Index()
    {
        _viewmodel.model = _context.MyModel.ToList();
        return View(_viewmodel);
    }

    public IActionResult Test()
    {
        var x = _viewmodel.buttonID; 
        return View();
    }
}

ViewModel:

public class HomeViewModel
    {
        public IEnumerable<MyModel> model { get; set; }
        public int buttonID { get; set; }
    }

View:

@model MyProject.ViewModels.HomeViewModel
<table>
    @foreach (var item in Model.model)
    {
        <tr>
            <td>
                 <form asp-controller="Home" asp-action="Test">
                        <button value="Add"/>
                  </form> 
            </td>
        </tr>
    }
</table>

What should be done in the view such that I can set the value of 'buttonID' of the viewmodel so that it is available in the controller?

in ASP MVC RAZOR

I want to create a button that when clicked it will add a TextBoxFor and on postback i want to get the inputted value from the textboxes created.

Help is much appreciated :)

I put font references to sub domain and I using that like this:

<link href="https://cdn.example.com/Styles/font-awesome.min.css" rel="stylesheet" />

Font from origin 'https://cdn.example.com' has been blocked from loading by Cross-Origin Resource Sharing policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'https://example.com' is therefore not allowed access.

I found a solution but it doesn't help me, I think the reason is I use https instead of http.

Serving contain to sub domains from an MVC / IIS web application

This is my .aspx code:

<asp:Panel ID="buses" runat="server">

    <asp:Panel ID="bus1" runat="server" CssClass="Bangalore Mumbai Delhi"></asp:Panel>
    <asp:Panel ID="bus2" runat="server" CssClass="Bangalore Kolkata Delhi Chennai"></asp:Panel>
    <asp:Panel ID="bus3" runat="server" CssClass="Chennai Mumbai Kolkata"></asp:Panel>

</asp:Panel>    

What I want to do is specify an if-condition and if a panel inside "buses" satisfies the condition, its ID should be retrieved.

For example, if the CssClass property of "bus1" contains "Bangalore", then its ID i.e. "bus1" should be retrieved.

Please note: The conditions should be checked for the panels inside "buses" only.

What code should I use in the .aspx.cs file to achieve this?

I have made Javascript file which contains some basic functions and used them in MASTERPAGE

 <script src="../assets/global/js/OtherFunctions.js"></script>

and I am calling them from asp.net textbox but not working but when I use them inside page then it works, why ?

.js function Clear() { location.reload(true);

}

function GetConfrim() {
    if (confirm("Are You Sure ?")) {
        return true;
    } else {
        return false;
    }
}

function isNumberKey_txtBoxComplaintContactNo(evt) {
    var charCode = (evt.which) ? evt.which : event.keyCode
    if (charCode > 31 && (charCode < 48 || charCode > 57) && charCode != 43) {
        return false;
    }
    return true;
}

function isNumberKeyCNIC(evt) {
    var charCode = (evt.which) ? evt.which : event.keyCode
    if (charCode > 31 && (charCode < 48 || charCode > 57) && charCode != 45)
        return false;

    return true;
}

textbox:

<asp:TextBox runat="server" ID="txtBoxComplainantMobileNo" MaxLength="14" ClientIDMode="Static" onkeypress="return isNumberKey_txtBoxComplainantContactNo(this)" CssClass="form-control"> </asp:TextBox>

i have tried to import from excel to dataset and error message occurs' hmmm i don't know whats wrong with the codes, Im currently studying this site http://vb.net-informations.com/excel-2007/vb.net_excel_oledb.htm

Imports System.Data

Imports System.Data.SqlClient

Public Class Form1

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Try
            Dim MyConnection As System.Data.OleDb.OleDbConnection
            Dim DtSet As DataSet
            Dim MyCommand As System.Data.OleDb.OleDbDataAdapter
            Dim Loc As String = Application.StartupPath() + "\Param\exceldata.xlsx"
            Dim strCOleCon As String = "provider=Microsoft.Jet.OLEDB.4.0; Data Source='" + Loc.Trim + "';Extended Properties=Excel 8.0;"

            MyConnection = New OleDb.OleDbConnection(strCOleCon)
            MyCommand = New OleDb.OleDbDataAdapter("select * from [Sheet1$]", MyConnection)
            MyCommand.TableMappings.Add("Table", "TestTable")
            DtSet = New DataSet
            MyCommand.Fill(DtSet)
            DataGridView1.DataSource = DtSet.Tables(0)
            MyConnection.Close()

        Catch ex As Exception
            MsgBox(ex.ToString)
        End Try
    End Sub

End Class

How to Fill text boxes when enter from footer textbox text changed event, i tried to fill item template text boxes but it shows the object reference error..

when iam entering item template textbox text changed event, it fill the data all text boxes..

let me know the solution..

enter image description here

ASP.NET

 <asp:GridView ID="gvwOrder" runat="server" ShowFooter="True" AutoGenerateColumns="False"
                                        CellPadding="4" ForeColor="#c00317" GridLines="None" CssClass="mGrid" PagerStyle-CssClass="pgr"
                                        OnRowDeleting="gvwOrder_RowDeleting">
                                        <Columns>
                                            <asp:BoundField DataField="RowNumber" HeaderText="SNo" />
                                            <asp:TemplateField HeaderText="Part Number">
                                                <ItemTemplate>
                                                    <%--<asp:DropDownList ID="ddlItemName" runat="server" AutoPostBack="true" AppendDataBoundItems="true"
                                        Width="300px" OnSelectedIndexChanged="ddlItemName_SelectedIndexChanged" au>
                                    </asp:DropDownList>--%>
                                                    <asp:TextBox ID="txtCatalogPartNumber" runat="server" AutoPostBack="true" Width="200px"
                                                        PlaceHolder="Part Number" CssClass="textbox" OnTextChanged="txtCatalogPartNumber_TextChanged"></asp:TextBox>
                                                    <ajaxToolkit:AutoCompleteExtender ServiceMethod="SearchtxtCatalogPartNumber" MinimumPrefixLength="1"
                                                        CompletionInterval="100" EnableCaching="false" CompletionSetCount="10" TargetControlID="txtCatalogPartNumber"
                                                        CompletionListCssClass="autocomplete_completionListElement" CompletionListItemCssClass="AutoExtenderList"
                                                        CompletionListHighlightedItemCssClass="AutoExtenderHighlight" ContextKey="True"
                                                        ID="AutoCompleteExtender1" runat="server" FirstRowSelected="true">
                                                    </ajaxToolkit:AutoCompleteExtender>
                                                    <asp:RequiredFieldValidator ID="rqdCatalogPartNumber" runat="server" ValidationGroup="valInsert"
                                                        SetFocusOnError="true" Display="None" ControlToValidate="txtCatalogPartNumber"
                                                        InitialValue="0" ErrorMessage="Select Catalog Part Number!.."></asp:RequiredFieldValidator>
                                                    <ajaxToolkit:ValidatorCalloutExtender runat="Server" ID="vceCatalogPartNumber" TargetControlID="rqdTax"
                                                        Enabled="true" />
                                                </ItemTemplate>
                                                <FooterStyle HorizontalAlign="Left" />
                                                <FooterTemplate>
                                                    <asp:Button ID="ButtonAdd" runat="server" CssClass="button" Text="Add New" onkeyup="Multiply(this);"
                                                        OnClick="ButtonAdd_Click" Visible="false" />
                                                    <%--<a href="#" onclick="OpenWindow();" style="color: White;">Search</a>--%>
                                                    <asp:TextBox ID="txtItemName" runat="server" AutoPostBack="true" Width="200px" PlaceHolder="Click Here For Search By Item Name"
                                                        CssClass="searchtextbox" OnTextChanged="txtItemName_TextChanged"></asp:TextBox>
                                                    <ajaxToolkit:AutoCompleteExtender ServiceMethod="SearchtxtItemName" MinimumPrefixLength="1"
                                                        CompletionInterval="100" EnableCaching="false" CompletionSetCount="2" TargetControlID="txtItemName"
                                                        CompletionListCssClass="autocomplete_completionListElement" CompletionListItemCssClass="AutoExtenderList"
                                                        CompletionListHighlightedItemCssClass="AutoExtenderHighlight" ContextKey="True"
                                                        ID="AutoCompleteExtender2" runat="server" FirstRowSelected="true">
                                                    </ajaxToolkit:AutoCompleteExtender>
                                                </FooterTemplate>
                                            </asp:TemplateField>
                                            <asp:TemplateField HeaderText="Unit" Visible="false">
                                                <ItemTemplate>
                                                    <asp:TextBox ID="txtUnitName" runat="server" Text="" Width="100px" ReadOnly="true"
                                                        PlaceHolder="Unit" CssClass="textbox"></asp:TextBox>
                                                </ItemTemplate>
                                            </asp:TemplateField>
                                            <asp:TemplateField HeaderText="Price">
                                                <ItemTemplate>
                                                    <asp:TextBox ID="txtItemPrice" runat="server" Text="" Width="80px" ReadOnly="true"
                                                        PlaceHolder="Price" CssClass="textbox"></asp:TextBox>
                                                </ItemTemplate>
                                            </asp:TemplateField>
                                            <%-- <asp:BoundField DataField="UnitName" HeaderText="Unit" />
                                                <asp:BoundField DataField="ItemPrice" HeaderText="Price" />--%>
                                            <asp:TemplateField HeaderText="Qty">
                                                <ItemTemplate>
                                                    <asp:TextBox ID="txtQty" runat="server" AutoPostBack="true" Text="1" Width="30px"
                                                        PlaceHolder="Qty" CssClass="textbox" onkeyup="funcsums();" OnTextChanged="txtQty_TextChanged"></asp:TextBox>
                                                </ItemTemplate>
                                            </asp:TemplateField>
                                            <asp:TemplateField HeaderText="Gross Amount">
                                                <ItemTemplate>
                                                    <asp:TextBox ID="txtGrossAmount" runat="server" Text="" Width="80px" ReadOnly="true"
                                                        PlaceHolder="Gross Amount" CssClass="textbox"></asp:TextBox>
                                                </ItemTemplate>
                                            </asp:TemplateField>
                                            <asp:TemplateField HeaderText="Remarks">
                                                <ItemTemplate>
                                                    <asp:TextBox ID="txtRemarks" runat="server" Text="" Width="130px" TextMode="MultiLine"
                                                        PlaceHolder="Remarks" CssClass="textbox"></asp:TextBox>
                                                </ItemTemplate>
                                            </asp:TemplateField>
                                            <asp:CommandField ShowDeleteButton="True" />
                                        </Columns>
                                        <FooterStyle BackColor="#535353" Font-Bold="True" ForeColor="White" />
                                        <AlternatingRowStyle BackColor="White" />
                                    </asp:GridView>

C#

protected void txtCatalogPartNumber_TextChanged(object sender, EventArgs e)
    {
        try
        {
            //string hifvalue = hdnItemID.Value;
            TextBox txtCurrentCatalogPartNumber = (TextBox)sender;
            GridViewRow currentDropDownList = ((GridViewRow)txtCurrentCatalogPartNumber.Parent.Parent);
            TextBox txtCatalogPartNumber = (TextBox)currentDropDownList.FindControl("txtCatalogPartNumber");
            TextBox txtUnitName = (TextBox)currentDropDownList.FindControl("txtUnitName");
            TextBox txtItemPrice = (TextBox)currentDropDownList.FindControl("txtItemPrice");
            TextBox txtQty = (TextBox)currentDropDownList.FindControl("txtQty");
            TextBox txtGrossAmount = (TextBox)currentDropDownList.FindControl("txtGrossAmount");
            TextBox txtRemarks = (TextBox)currentDropDownList.FindControl("txtRemarks ");

            string[] splitval = new string[50];
            splitval = txtCatalogPartNumber.Text.Split('~');
            var val = from s in splitval
                      select s;
            int arrcount = val.Count();
            if (arrcount == 3)
            {
                string itemid = splitval[2];
                bolItem.ItemCode = itemid;

                DataTable dt = bolItem.GetItemByItemID();
                if (dt.Rows.Count > 0)
                {
                    txtItemPrice.Text = dt.Rows[0]["MRP"].ToString();
                    txtGrossAmount.Text = dt.Rows[0]["MRP"].ToString();

                    txtQty.Text = "1";
                    //txtGrossAmount.Text = dt.Rows[0][6].ToString();
                    txtCatalogPartNumber.Focus();
                    Total();
                    AddNewRow();
                }
            }
            else
            {
                txtCatalogPartNumber.Focus();
            }
        }
        catch (Exception ex)
        {
            ScriptManager.RegisterStartupScript(this, GetType(), "Error Message", "alert('" + ex.Message.ToString() + "')", true);
        }
    }

    protected void txtItemName_TextChanged(object sender, EventArgs e)
    {
        try
        {                
            //string hifvalue = hdnItemID.Value;
            TextBox txtCurrentCatalogPartNumber = (TextBox)sender;
            GridViewRow currentDropDownList = ((GridViewRow)txtCurrentCatalogPartNumber.Parent.Parent);
            TextBox txtCatalogPartNumber = (TextBox)currentDropDownList.FindControl("txtCatalogPartNumber");
            TextBox txtUnitName = (TextBox)currentDropDownList.FindControl("txtUnitName");
            TextBox txtItemPrice = (TextBox)currentDropDownList.FindControl("txtItemPrice");
            TextBox txtQty = (TextBox)currentDropDownList.FindControl("txtQty");
            TextBox txtGrossAmount = (TextBox)currentDropDownList.FindControl("txtGrossAmount");
            TextBox txtRemarks = (TextBox)currentDropDownList.FindControl("txtRemarks ");

            GridViewRow rows = gvwOrder.FooterRow;
            TextBox txt = (TextBox)rows.FindControl("txtItemName");
            string txtItemName = ((TextBox)gvwOrder.FooterRow.FindControl("txtItemName")).Text;



            string[] splitval = new string[50];
            splitval = txt.ToString().Split('~');
            var val = from s in splitval
                      select s;
            int arrcount = val.Count();
            if (arrcount == 3)
            {
                string itemid = splitval[2];
                bolItem.ItemCode = itemid;

                DataTable dt = bolItem.GetItemByItemID();
                if (dt.Rows.Count > 0)
                {
                    txtItemPrice.Text = dt.Rows[0]["MRP"].ToString();
                    txtGrossAmount.Text = dt.Rows[0]["MRP"].ToString();

                    txtQty.Text = "1";
                    //txtGrossAmount.Text = dt.Rows[0][6].ToString();
                    txtCatalogPartNumber.Focus();
                    Total();
                    AddNewRow();
                }
            }
            else
            {
                txtCatalogPartNumber.Focus();
            }
        }
        catch (Exception ex)
        {
            ScriptManager.RegisterStartupScript(this, GetType(), "Error Message", "alert('" + ex.Message.ToString() + "')", true);
        }
    }

This question already has an answer here:

My app is producing the error

Object reference not set to an instance of an object.

For some reason Postal is giving an error with the layouts in the root _ViewStart.cshtml specifically the first if statement which is shown below.

_ViewStart.cshtml

    if (this.User.IsInRole("Admin") || !this.User.Identity.IsAuthenticated)
{
    Layout = "~/Views/Shared/_Layout.cshtml";
}
else if (this.User.IsInRole("Territorial Strategic Planning Coordinator") || this.User.IsInRole("Programme Secretary") || this.User.IsInRole("IT") || !this.User.Identity.IsAuthenticated)
{
    Layout = "~/Views/Shared/_LayoutLevel1.cshtml";
}  
else if (this.User.IsInRole("Divison Commander") || !this.User.Identity.IsAuthenticated)
{
    Layout = "~/Views/Shared/_LayoutLevel2.cshtml";
}
else if (this.User.IsInRole("Corps Officer") || this.User.IsInRole("Centre Admin") || !this.User.Identity.IsAuthenticated)
{
    Layout = "~/Views/Shared/_LayoutLevel3.cshtml";
}

The code I'm using within my controller is :

 dynamic email = new Email("GoalNotification");
                email.ResponseID = goal.ResponseID;
                email.User = user.UserName;
                email.To = user.Email;
                email.Send();

and the Postal View is : GoalNotification.cshtml

To: @ViewBag.To
Subject: Goal Notification for Response : @ViewBag.ResponseID

<div>

    <p style="font-size:large; font-weight:bold">
        Dear @ViewBag.User
    </p>
    <p>
        This is a system generated notification to notify you that one or more of your goals need attention.
    </p>
    <p>
        Please revise and re-submit.
    </p>

    <p>Kind Regards</p>

    <p>TSP</p>
    ----------------------------------------------------------------------------------
    <p style="font-weight:100"><u>Contact Details</u></p>
    <p>Office Number: </p>
    <p>Email Address: </p>
    <p>Physical Address: </p>
    <hr />
</div>

Is there something I am doing wrong here? and is there any way to fix this? Its my first time using Postal. Thanks for any help.

Edit: Im only getting this error because MVC Postal seems to be overriding my root _ViewStart. The program runs normal without it.

Postal has an issue when there is more than one layout specified it seems. If i have one set layout it works. Unfortunately I need to have them.

The Stack Trace :

    [NullReferenceException: Object reference not set to an instance of an object.]
   ASP._Page_Views__ViewStart_cshtml.Execute() in c:\Users\Shahil\Desktop\TSPMVC Backups\2016\28-01-2016\TSP MVC\TSP MVC\Views\_ViewStart.cshtml:3
   System.Web.WebPages.StartPage.ExecutePageHierarchy() +73
   System.Web.WebPages.WebPageBase.ExecutePageHierarchy(WebPageContext pageContext, TextWriter writer, WebPageRenderingBase startPage) +131
   System.Web.Mvc.RazorView.RenderView(ViewContext viewContext, TextWriter writer, Object instance) +695
   System.Web.Mvc.BuildManagerCompiledView.Render(ViewContext viewContext, TextWriter writer) +382
   Postal.EmailViewRenderer.RenderView(IView view, ViewDataDictionary viewData, ControllerContext controllerContext, ImageEmbedder imageEmbedder) +182
   Postal.EmailViewRenderer.Render(Email email, String viewName) +204
   Postal.EmailService.CreateMailMessage(Email email) +72
   Postal.EmailService.Send(Email email) +65
   Postal.Email.Send() +56
   CallSite.Target(Closure , CallSite , Object ) +189
   System.Dynamic.UpdateDelegates.UpdateAndExecuteVoid1(CallSite site, T0 arg0) +432
   TSP_MVC.Controllers.GoalsController.AdminEdit(Goal goal) in c:\Users\Shahil\Desktop\TSPMVC Backups\2016\28-01-2016\TSP MVC\TSP MVC\Controllers\GoalsController.cs:195
   lambda_method(Closure , ControllerBase , Object[] ) +180
   System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters) +59
   System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters) +435
   System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +60
   System.Web.Mvc.Async.ActionInvocation.InvokeSynchronousActionMethod() +76
   System.Web.Mvc.Async.AsyncControllerActionInvoker.<BeginInvokeSynchronousActionMethod>b__39(IAsyncResult asyncResult, ActionInvocation innerInvokeState) +36
   System.Web.Mvc.Async.WrappedAsyncResult`2.CallEndDelegate(IAsyncResult asyncResult) +73
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +136
   System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +102
   System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult) +49
   System.Web.Mvc.Async.AsyncInvocationWithFilters.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3d() +117
   System.Web.Mvc.Async.<>c__DisplayClass46.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3f() +323
   System.Web.Mvc.Async.<>c__DisplayClass33.<BeginInvokeActionMethodWithFilters>b__32(IAsyncResult asyncResult) +44
   System.Web.Mvc.Async.WrappedAsyncResult`1.CallEndDelegate(IAsyncResult asyncResult) +47
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +136
   System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +102
   System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethodWithFilters(IAsyncResult asyncResult) +50
   System.Web.Mvc.Async.<>c__DisplayClass2b.<BeginInvokeAction>b__1c() +72
   System.Web.Mvc.Async.<>c__DisplayClass21.<BeginInvokeAction>b__1e(IAsyncResult asyncResult) +185
   System.Web.Mvc.Async.WrappedAsyncResult`1.CallEndDelegate(IAsyncResult asyncResult) +42
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +133
   System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +56
   System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult) +40
   System.Web.Mvc.Controller.<BeginExecuteCore>b__1d(IAsyncResult asyncResult, ExecuteCoreState innerState) +34
   System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +70
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +133
   System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +56
   System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +37
   System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +44
   System.Web.Mvc.Controller.<BeginExecute>b__15(IAsyncResult asyncResult, Controller controller) +39
   System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +62
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +133
   System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +56
   System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +37
   System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +39
   System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute(IAsyncResult asyncResult) +39
   System.Web.Mvc.MvcHandler.<BeginProcessRequest>b__5(IAsyncResult asyncResult, ProcessRequestState innerState) +39
   System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +70
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +133
   System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +56
   System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +37
   System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +40
   System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +38
   System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +9721605
   System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155

I have an ASP.NET MVC solution which references to another class library, in which i have an MVC folder and inside of it "Controller", "Model" and "View" folders. I'd like to do something like

@Html.ActionLink("Text", "Index", "DllController")

which will link to the DllController/Index action in the dll and show a view from that lib. Debugging through this, I see that it goes into the Controller, but once it reaches

return View("MyView", model);

I receive the foolowing error:

The view 'MyView' or its master was not found or no view engine supports the searched locations. The following locations were searched: ~/Views/MyView/MyView.aspx ~/Views/MyView/MyView.ascx ~/Views/Shared/MyView.aspx ~/Views/Shared/MyView.ascx ~/Views/MyView/MyView.cshtml ~/Views/MyView/MyView.vbhtml ~/Views/Shared/MyView.cshtml ~/Views/Shared/MyView.vbhtml ~/Mvc/Views/MyView/MyView.cshtml ~/Mvc/Views/Shared/MyView.cshtml

I assume this is because the view is being searched for in the current assembly. Can i change this behavior to show my imported view correctly?

I went to create an MVC app with Razor viewEngine today, but it's not there. I looked at online templates. I also tried closing/opening I also tried searching it.

I can't seem to find it anywhere. Web API exists, but I don't want that, I just want MVC with Razor viewEngine. I can open previous projects that use Razor but I can't open them!

I have the following html table definition in my main view

<table id="myDynamicTable" cellpadding="0" cellspacing="0" class="burTable" width="964px">
        <thead>
            <tr>
                <th style="white-space: nowrap;display: inline;width: 40px" >
                    ColOne
                </th>
                <th style="white-space: nowrap;display: inline;width: 90px">
                    ColTow
                </th>
                <th style="white-space: nowrap;display: inline;width: 54px">
                    ColThree
                </th>
                <th style="white-space: nowrap;display: inline;width: 60px">
                    ColFour
                </th>
                <th style="white-space: nowrap;display: inline;width: 399px">
                    ColFive
                </th>
                <th style="white-space: nowrap;display: inline;width: 474px">
                    ColSix
                </th>
            </tr>
        </thead>
        <tbody>
          @if (Model.myViewModel.Count() > 0)
            {
                int i = 1;
                foreach (var item in Model.myViewModel)
                {
                    <tr >
                        <td class="tdBorder">
                            @Html.DisplayFor(x => item.AutoNumber, new { @readonly = "readonly" })
                            @Html.HiddenFor(x => item.Code, new { id = "Code" + @i })
                        </td>
                        <td>
                            @Html.TextBoxFor(x => item.SerialNumber, new { id = "SerialNumber" + @i, @Class = "numberOnly", maxlength = 15 })
                        </td>
                        <td>
                            @Html.DropDownList("ddlItemType" + @i, new SelectList(ViewBag.ddlItemTypeList as System.Collections.IEnumerable, "Value", "Text", item.ItemTypeId))
                        </td>
                        <td>
                            @Html.TextBoxFor(x => item.Date, new { id = "Date" + @i })
                        </td>
                        <td>
                            @Html.DropDownList("ddlUnit" + @i, new SelectList(ViewBag.UnitList as System.Collections.IEnumerable, "Value", "Text", item.UnitId))
                        </td>
                        <td>
                            @Html.TextBoxFor(x => item.Comment, new { id = "Comment" + @i, @class = "Comment RestrictCharacters", maxlength = 1000 })
                        </td>
                    </tr>
                    i += 1;
                }

            }
            else
            {
                <tr id="FirstRow" class="tdBorder">
                    <td class="tdBorder">
                       @Html.TextBox("AutoNumber", null, new { @width = 60, id = "AutoNumber" })
                    </td>
                    <td>
                        @Html.TextBox("SerialNumber", null, new { @width = 150, id = "SerialNumber" })
                    </td>
                    <td>
                         @Html.DropDownList("ddlItemType", new SelectList(ViewBag.ddlItemTypeList as System.Collections.IEnumerable, "Value", "Text"), new { @width = 60, id = "ddlItemType" })
                    </td>
                    <td>
                        @Html.TextBox("Date", null, new { @width = 60, id = "Date" })
                    </td>
                    <td>
                        @Html.DropDownList("ddlUnit", new SelectList(ViewBag.UnitList as System.Collections.IEnumerable, "Value", "Text"), new { @width = "auto", id = "ddlUnit" })
                    </td>
                    <td>
                        @Html.TextBox("Comment", null, new { @width = 700, id = "Comment" })
                    </td>
                </tr>
            }
        </tbody>
    </table>

I want to be able to add new rows using the BeginCollectionItem concept explained in here http://blog.stevensanderson.com/2010/01/28/editing-a-variable-length-list-aspnet-mvc-2-style/ and Add row in table with jquery whic connected with model in mvc

Below is the definition of my partial view which i want to use as a template to add new rows. @using MyProject.Utilities @model MyProject.ViewModel.ReportDetailsViewModel

@using (Html.BeginCollectionItem("NewRow"))
{
    <tr id="NewRow" class="tdBorder">
        <td class="tdBorder">
            @Html.TextBox("AutoNumber", null, new { @width = 60, id = "AutoNumber" })
        </td>
        <td>
            @Html.TextBox("SerialNumber", null, new { @width = 150, id = "SerialNumber" })
        </td>
        <td>
            @Html.DropDownListFor(model => model.ItemTypeId, Model.ItemTypeList, new { @id = "ddlItemType" })
        </td>
        <td>
            @Html.TextBox("Date", null, new { @width = 60, id = "Date" })
        </td>
        <td>
            @Html.DropDownList("ddlUnit", new SelectList(ViewBag.UnitList as System.Collections.IEnumerable, "Value", "Text"), new { @width = "auto", id = "ddlUnit" })
            @Html.DropDownListFor(model => model.UnitId, Model.UnitList)
        </td>
        <td>
            @Html.TextBox("Comment", null, new { @width = 700, id = "Comment" })
        </td>
    </tr>
}

In my main view, i'm trying to add new rows like below

 var tableBody = $('#myDynamicTable tbody');
    var url = '@Url.Action("Add", "Report")';
    $('#btnAddRow').click(function () {
        $.get(url, function (response) {
            tableBody.append(response);
        });
    });

The problem is, it appears like the rows are being added after the table body but not inside the body after the last row.

The other issue i'm having is the new row columns not aligning with the existing first row as well as also not picking the style sheets applied to the controls in the existing first row.

Below is the screenshot of what i'm so far getting and i'm struggling to alight these new rows with the existing first row.

Screenshot of table

I have following list view

enter image description here

Once I click Reject I just configured to open a modal dialog like following

enter image description here

So Once I submit this modal dialog I want to submit modal values to method to save that in database table.

this is relevant model classes

    public class ProductViewModel
    {
        public AB_Product Products { get; set; }
        public IEnumerable<AB_Product> LProducts { get; set; }
    }

    public partial class AB_Product
    {
        public string ProductID { get; set; }
        public string ApprovalStatus { get; set; }
        public string ReasonEn { get; set; }
        public string ReasonAr { get; set; }
    }

this is view page code

@model project_name.Models.ProductViewModel

<table class="table">

    <tr>
        <th>
            Name
        </th>
        <th>
            Action
        </th>
    </tr>

    @foreach (var obj in Model.LProducts)
    {
        <tr>
            @Html.HiddenFor(modelItem => obj.ProductID)

            <td>
                @Html.DisplayFor(modelItem => obj.ProductTitleEn)
            </td>

            <td>

                <div class="btn-group btn-group-sm" id="CreateButton">
                    <button type="button" class="btn btn-default" onclick="location.href='@Url.Action("Create")';return false;">View Product</button>
                </div>

                @if (obj.ApprovalStatus == "Pending")
                {
                    <div class="btn-group btn-group-sm" id="ApproveButton">
                        <button type="button" class="btn btn-success" onclick="location.href='@Url.Action("Change_Product_State","Home", new { productid = obj.ProductID, value = "Approved" },null)';return false;">Approve</button>
                    </div>

                    <div class="btn-group btn-group-sm" id="RejectButton">
                        <button type="button" id="modal-opener" class="btn btn-danger" return false;">Reject</button>
                    </div>

                }

                <div class="btn-group btn-group-sm" id="CreateButton">
                    <button type="button" class="btn btn-primary" onclick="location.href='@Url.Action("Create_ProductComments","Home", new { productid = obj.ProductID }, null)';return false;">Add Comments</button>
                </div>

            </td>

        </tr>
    }

</table>


<div id="dialog-modal" title="Basic modal dialog">
    @using (Ajax.BeginForm("Change_Product_State", "Home", new { value = "Rejected" }, new AjaxOptions { UpdateTargetId = "ID", OnSuccess = "onSuccess" }))
    {
        <div>
            <fieldset>
                <legend>Account Information</legend>

                <div class="editor-label">
                    @Html.LabelFor(m => m.Products.ReasonEn)
                </div>

                <div class="editor-field">
                    @Html.TextAreaFor(m => m.Products.ReasonEn)
                    @Html.ValidationMessageFor(m => m.Products.ReasonEn)
                </div>

                <div class="editor-label">
                    @Html.LabelFor(m => m.Products.ReasonAr)
                </div>

                <div class="editor-field">
                    @Html.TextAreaFor(m => m.Products.ReasonAr)
                    @Html.ValidationMessageFor(m => m.Products.ReasonAr)
                </div>

                <p>
                    <input type="submit" value="Submit" />
                </p>

            </fieldset>
        </div>
    }
</div>


@section Scripts
{

<script>
        $(function () {
            $("#dialog-modal").dialog({
                autoOpen: false,
                width: 400,
                height: 400,
                show: {
                    effect: "blind",
                    duration: 1000
                },
                hide: {
                    effect: "explode",
                    duration: 1000
                }
            });

            $("#modal-opener").click(function () {
                 $("#dialog-modal").dialog("open");
            });
        });

        function onSuccess() {
            $("#dialog-modal").dialog("close");
        }
</script>

}

how to bind list object I click which is ProductID with m.Products.ProductID

I am trying to follow this example to create 2 tabs; I include the scripts as explained in this question.

The result is as if there is no javascript at all.

What am doing wrong and how to fix it?

View:

@model WebApplication1.Models.TheTableInformation

@{
    ViewBag.Title = "Show, Modify and Download a Table";
}

@using (Html.BeginForm("Act", "Excel", FormMethod.Post, new { tableInfo = Model }))
{
    <p>
        Find by table name: @Html.EditorFor(m => m.TheName)           
        <input type="submit" name="command" value="Show On The Page" />
    </p>

    <div id="tabs">    
        <ul>
            <li><a href="#tabs-Data">Data</a></li>
            <li><a href="#tabs-History">History</a></li>
        </ul>

        <div id="tabs-Data">
            ...
        </div>    
        <div id="tabs-History">         
            ...
        </div> 
    </div>
}

@section Scripts {
    <script src="@System.Web.Optimization.BundleTable.Bundles.ResolveBundleUrl(
        "~/Content/themes/base/base")"></script>
    <script src="@System.Web.Optimization.BundleTable.Bundles.ResolveBundleUrl(
        "~/Scripts/jquery-ui-{version}.min.js")"></script>
    <script src="@System.Web.Optimization.BundleTable.Bundles.ResolveBundleUrl(
        "~/Scripts/jquery-{version}.min.js")"></script>
    <script type="text/javascript">
        $(function () {
            $("#tabs").tabs();
        });
    </script>
}

BundleConfig.cs

    public static void RegisterBundles(BundleCollection bundles)
    {
        bundles.Add(new StyleBundle("~/Content/themes/base/base").Include(
                     "~/Content/themes/base/base.css"));

        bundles.Add(new ScriptBundle("~/bundles/jqueryuimin").Include(
                    "~/Scripts/jquery-ui-{version}.min.js"));

        bundles.Add(new ScriptBundle("~/bundles/jquerymin").Include(
                    "~/Scripts/jquery-{version}.min.js"));
       ...
   }

Resulting Code Source (fragment)

<script src="/bundles/jquery?v=2BDNJmnbg3aRp0e0_W5EfbuETd2F7HgQ62imnNha1A41"></script>

<script src="/bundles/bootstrap?v=2Fz3B0iizV2NnnamQFrx-NbYJNTFeBJ2GM05SilbtQU1"></script>


<script src="/Content/themes/base/base?v=PRoqfZz0EsUttHCzAfkRuCxIvrKrMaXCB2K4VnmM0p81"></script>
<script src="/bundles/jqueryuimin?v=EqKlUEwb5a6QnKK9APLpZeOKZkAYzlO2YiCGDkzKK6c1"></script>
<script src="/bundles/jquerymin?v=2BDNJmnbg3aRp0e0_W5EfbuETd2F7HgQ62imnNha1A41"></script>
<script type="text/javascript">
    $(function () {
        $("#tabs").tabs();
    });
</script>

Packages.config (fragment)

  <package id="jQuery" version="2.2.0" targetFramework="net451" />
  <package id="jQuery.UI.Combined" version="1.11.4" targetFramework="net451" />
  <package id="jQuery.Validation" version="1.11.1" targetFramework="net451" />

Bit of a long winded question - I'm basically using the toggle function from Bootstrap to show and hide a text box when clicking a button. My issue is, the text box and button is used for each item in a list which is dynamically loaded so I can't assign IDs via HTML as usual.

How can I generate a different ID for each text box and add that ID to each text box's button's href tag?

Here's my code of the text box and button (which sits inside an li tag along with some other information which gets generated for each item in the list):

<div id="comment-container">
    <a data-toggle="collapse" href="" aria-expanded="false" aria-controls="add-comment" class="btn btn-primary add-comment"><i class="fa fa-plus-circle"></i><span>Add Comment</span></a>
    @Html.TextAreaFor(x => Model.CurrentStage.Responses[i].Comment, new { @class = "form-control comment collapse", rows = 3, placeholder = "Enter a comment to accompany your response here:" })
</div>

I've played about with some snippets of jquery, but nothing's quite worked so far.

Here's how it should look when it works: Screenshot