In MVC, every class should belong to either View, Model or Controller. View and Model should not know about each other. Therefore, this is bad:

@interface Person : NSObject    // Clearly a model class

@property (nonatomic) NSString *name;
@property (nonatomic) NSUInteger age;


@interface PersonInfoView : NSView    // Clearly a view class

@property (nonatomic) Person *personToDisplay;


Instead, you would configure the PersonInfoView from the controller. So you might instead have this PersonInfoView class:

@interface PersonInfoView : NSView

@property (nonatomic) NSString *nameToDisplay;
@property (nonatomic) NSUInteger ageToDisplay;


But as you see, NSString is in both a model and a view class! The only explenation would be that NSString is a controller, but that doesn't make sense at all.

My thought was then, maybe NSString (and similiar classes) are excluded becasue they almost act as primitive C types?

here is my controller:

  'use strict';

    .controller('HomeController', ['Factory',

    function HomeController(Factory){

      var result = Factory.query();

      this.model = result[0];


in the view I get the value by doing so

div(ng-controller='HomeController as HomeCtrl')

the problem is I don't get any value. I am totally sure the value is returned from the factory since I have already tested the Factory.query() and I got the results. In fact If I do in the following way and get the value in the view by doing HomeCtrl.result[0], I get the result.

  'use strict';

    .controller('HomeController', ['Factory',

    function HomeController(Factory){

      this.result = Factory.query();


I have a text box and a button upon clicking which should retrieve the value set in the text box and pass it to a controller. I am trying to do this by calling a JQuery function which returns me the value of text box and pass as routevalues parameter. I know this does not work, but my question is there a way to modify the below code to achieve this? Basically i want to know how can I plug getValue function inside ActionLink call.

<script type="text/javascript">
$(function () {

    var getValue = function () {

        return $("#addtoset").val();

@Html.TextBox("addtoset", "", htmlAttributes : new { @id = "addtoset", @class = "col-sm-10" })
@Html.ActionLink("Add To Set", "AddToSet", routeValues: new { amount = getValue()}, htmlAttributes : new { @id="linkSet", @class = "col-sm-2" }) 

Warning: I am an IIS/ASP/Razor newb. I am using VS2013.

I have a solution with 2 web projects, let's call then Main and Methods. Main is a Razor MVC project, and Methods is just a generic web project. Methods references Main. I am attempting to add and use connection strings to the web.config file for Methods.

However, when I attempt to access the strings in a function, they are not available. I have discovered that this is probably because the web.config file that is being loaded is the one for the Main project, instead of Methods (according to AppDomain.CurrentDomain.SetupInformation.ConfigurationFile).

Why might this be?

I am using below javascript code. I want to stay on same page till user click on alert. After click on alert page should redirect to SomePage.aspx

<script type="text/javascript">
    function myFunction() {
        alert("Some text...");
        window.location = 'SomePage.aspx';

Please let me know what I missed here. Thanks.


int sum;

sum= txt.Text + txt2.Text;

I have a simple aspx and aspx.cs file in which i am calculate sum of two numbers but now i want make a dll of aspx.cs .

now i want only dll of default.aspx.cs file

i dont wont aspx.cs file in my site.

i have visited many solutios but i didnt find the proper way to implement it.

and what is the diiference if i make dll instead of aspx.cs file.?

Give me the solution in step by step manner..

Thank you

In the cshtml file, I have the following javascript in Home/Details/4. 4 is the ID.

    $(document).ready(function () {
        $("#checkbox").click(function () {
            $.post("Home/Toggle", { going: $("#checkbox").val() }, function (data) {


The following is the action code in the controller.

    public ActionResult Toggle(bool checkbox)
        ...... // How to get ID?
        var x = db.XXXX.Find(id);

How to get the ID? From some routing data, or Url, or let the front jQuery posting pass it?

Default ASP Menu pops up when using mouse-over on Computer. On modern touch systems that could be a problem. On mobile app, the mouse-over does not exist and if user clicks on the ASP menu, the menu pops up but disappears before user can select menu child items.

How to allow touch-screen users to work with ASP menu?

    <form id="form1" runat="server">

            <asp:Menu ID="cmbMyAccount" runat="server" Orientation="Horizontal" DisappearAfter="5000">
                    <asp:MenuItem Text="My Account" Value="My Account" Selectable="False">
                        <asp:MenuItem Text="My Orders" Value="My Orders" NavigateUrl="~/MyOrders/index.aspx" />
                        <asp:MenuItem Text="Wish List" Value="Wish List" NavigateUrl="~/MyOrders/WishList.aspx" />
                        <asp:MenuItem Text="My Profile" Value="My Profile" NavigateUrl="~/MyProfile/index.aspx" />


Live demo:

In my mvc application I am getting 406 when my cshtml file tries to load the js file. something like this

GET http://localhost/Scripts/App/Dashboard.js?_=1408764995728
406 Not Acceptable

Request Header's says: Accept: application/json

Whereas Response header says; Content-Type: text/html; charset=utf-8

If I run the same on a postman I get the result with response header as Content-Type →application/javascript

Any clue on this.

I'm posting and answering my own question in case it helps someone else - I just spend several hours trying to figure out why I was getting a 404 error for the code-behind of an ASPX page. We had converted an existing web site to a web application and published to Azure. The web page worked properly during testing on localhost (IIS-Express), but threw the 404 error when running on Azure.

I'm new to ASP.NET MVC and SQL Server.

I know that is possible to upload file from view (page and form) and save it in database; Also I know that FTP access is a separated subject from database. I can create list to show files which stored in database (maybe on http:// but we know that it isn't real FTP listing and we cannot remote it.

Here is my question: Can we configure server to save FTP files to database and manage it with real FTP protocol (ftp://)?



Why doesn't the System.Web.Caching.Cache onUpdateCallback respect the absolutionExpiration time?


I'm experimenting with creating a cache strategy that will automatically refresh itself after a given interval. However, I want the cache to refresh on the background thread instead of evicting and then waiting for a new user request to force a cache refresh. I've elected to use the onUpdateCallback to repopulate the cache once the absolute expiration has been reached.


I've created a sample Controller to illustrate this:

public class ExampleController : Controller
    private const string CacheKey = "Test";

    //Simple function to get current time
    private readonly Func<string> GetTime = 
        () => DateTime.Now.ToString("HH:mm:ss fff");

    //Cache for 5 seconds
    private readonly TimeSpan _cacheDuration = new TimeSpan(0, 0, 5);

    private static bool _cacheWarmed = false;

    private void WarmCache()
        if (_cacheWarmed)

        _cacheWarmed = true;

        //Cache current time
                key: CacheKey,
                value: GetTime(),
                dependencies: null,
                absoluteExpiration: DateTime.Now.Add(_cacheDuration),
                slidingExpiration: Cache.NoSlidingExpiration,
                //On cache eviction - cache current time (ie eviction time)
                      (string s,
                        CacheItemUpdateReason reason,
                        out object cachedItem,
                        out CacheDependency dependency,
                        out DateTime expiration,
                        out TimeSpan slidingExpiration) =>
                          expiration = DateTime.Now.Add(_cacheDuration);
                          cachedItem = GetTime();
                          dependency = null;
                          slidingExpiration = Cache.NoSlidingExpiration;

    public ActionResult Subscribe()

        return new ContentResult 
             Content =  (string)HttpContext.Cache.Get(CacheKey) 

And a simple Html with some javascript to call the method over and over again and output the result:

<script type="text/javascript">
    $(document).ready(function() {
        var myFunc = function()
            var startTime = new Date().getTime();

                url: "/join/subscribe"
            }).done(function(data) {

                var currentTime = new Date();

                var msg =
                    currentTime.toLocaleTimeString() +
                    ": [" +
                    data +
                        "] - Executed in " +
                        (currentTime.getTime() - startTime) +
                        " ms <br/>";



        var intervalHandle = setInterval(myFunc, 2000);



Truncated for brevity:

 3:45:52 PM: [15:45:40 387] - Executed in 30 ms 
 3:45:55 PM: [15:45:40 387] - Executed in 4 ms 
 3:45:57 PM: [15:45:40 387] - Executed in 4 ms 
 3:45:59 PM: [15:45:40 387] - Executed in 4 ms 
 3:46:01 PM: [15:46:00 399] - Executed in 4 ms 
 3:46:03 PM: [15:46:00 399] - Executed in 4 ms 
         (duplicates removed - :04 - :18)
 3:46:19 PM: [15:46:00 399] - Executed in 3 ms 
 3:46:21 PM: [15:46:20 406] - Executed in 4 ms 
 3:46:23 PM: [15:46:20 406] - Executed in 3 ms 
         (duplicates removed - :24 - :38)
 3:46:39 PM: [15:46:20 406] - Executed in 3 ms 
 3:46:41 PM: [15:46:40 418] - Executed in 3 ms 
 3:46:43 PM: [15:46:40 418] - Executed in 3 ms 
         (duplicates removed - :44 - :58)
 3:46:59 PM: [15:46:40 418] - Executed in 3 ms 
 3:47:01 PM: [15:47:00 419] - Executed in 3 ms 
 3:47:03 PM: [15:47:00 419] - Executed in 3 ms 

The method is cached for 20 seconds, even though I set the timeout for 5!

I've experimenting with changing the cache duration:

  • _cacheDuration = new TimeSpan(0, 0, 1) - No change
  • _cacheDuration = new TimeSpan(0, 0, 10) - No change
  • _cacheDuration = new TimeSpan(0, 0, 20) - No change
  • _cacheDuration = new TimeSpan(0, 0, 25) - Cached for 40 seconds

Question Reprise

So what's going on here? Why is cache duration not respected? Or did I not setup the Cache correctly?

i have a gridview which is binded to a table in sql server . i wrote a c# code at code behind i.e :

    protected void Page_Load(object sender, EventArgs e)
        SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["myconectionstring"].ConnectionString);
        SqlCommand cmd = new SqlCommand("select fldCompany,fldModel 'مدل',fldYear 'سال',fldPrice 'قیمت',fldCountPhoto  'تعداد عکس',fldActive  'موقعیت نمایش' from tbl_Usercar where fldTbl_UserID =@fldTbl_UserID", con);
        cmd.Parameters.AddWithValue("@fldTbl_UserID", Session["se_userID"] as string);
        SqlDataAdapter da = new SqlDataAdapter(cmd);
        DataSet ds = new DataSet();





now my table appear as i want to but i cant change my gridview style Eg i can't change the Columns color or font and etc . i tried to use my datasource and make attribute in my asp page but it will show each Columns 2 times .

please help me to fix this problem . Thank you

I've got a function to draw a line graph as shown below. The data points are obtained from a MySQL table. However, how can I number each data point in the x axis 1,2,3,4...?

In the example below, the query returns two results and the graph displays the two points so the graph should have 1 and 2 marked on the axis.

EDIT: Initial problem solved. However, for the example above, there are 2 data points but the max x value is 3. Is there a way of setting the maximum x value to equal the number of data points?

line graph

protected void chart(int moduleID)
    string connStr = ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString;
    MySqlConnection conn = new MySqlConnection(connStr);

    string comm = "SELECT * FROM scores WHERE test_id=0 AND module_id=@ModuleID AND user_id=@UserID";
    MySqlCommand mySqlCommand = new MySqlCommand(comm, conn);
    mySqlCommand.Parameters.Add(new MySqlParameter("@ModuleID", moduleID));
    mySqlCommand.Parameters.Add(new MySqlParameter("@UserID", Session["UserID"]));

    MySqlDataAdapter dataAdapter = new MySqlDataAdapter(mySqlCommand);
    DataTable ds = new DataTable();

    Chart1.ChartAreas["ChartArea1"].AxisX.MajorGrid.Enabled = false;
    Chart1.ChartAreas["ChartArea1"].AxisY.MajorGrid.Enabled = false;
    Chart1.ChartAreas["ChartArea1"].AxisX.Minimum = 1;
    Chart1.ChartAreas["ChartArea1"].AxisX.LabelStyle.Enabled = false;
    Chart1.ChartAreas["ChartArea1"].AxisX.Title = "attempt no.";
    Chart1.ChartAreas["ChartArea1"].AxisY.Minimum = 0;
    Chart1.ChartAreas["ChartArea1"].AxisY.Maximum = 100;
    Chart1.ChartAreas["ChartArea1"].AxisY.Title = "%";
    Chart1.ChartAreas["ChartArea1"].AxisY.TextOrientation = TextOrientation.Horizontal;


        if (ds.Rows.Count > 0)
            Chart1.DataSource = ds;
            Chart1.Series["Series1"].YValueMembers = "score";
            Chart1.Visible = false;
            lblError2.Text = "No results found.";
        lblError.Text = "Database connection error. Unable to obtain data at the moment.";

I have a model called question :

 public partial class question
        public question()
            this.Indicators = new HashSet<Indicator>();

        public int Id { get; set; }
        public string questionText{ get; set; }

        public virtual ICollection<Indicator> asnwers{ get; set; }

This model have 2 attributes called id and questiontext my model has a relation with answer Model .Every question has 1..n answer .In my answer model i have this :

 public partial class answer
        public answer()

        public int Id { get; set; }
        public int questionId{ get; set; }
        public string answertext{ get; set; }

        public virtual question ExecutiveOfficer { get; set; }

So as you can see every question has 1 or many answer .Let me explain my problem .

I need to show my questions to user in view but my problem is how can i create dynamic DDL answers and questions .

My user should be able to answer the dynamic questions and in controller i should be able to detect each question's answer but i don't know which kind of method should i use?i will be appreciate if you will give me some help .

I wanted to create HTML drop down list and pass them to view but i want to know if therer is a better solution i use that .

I have the following in a datagrid using .NET 2:

<asp:HyperLink runat="server" NavigateUrl='<%# "edit.aspx?f=" & DataBinder.Eval(Container.DataItem, "forum_id") & "&t=" & DataBinder.Eval(Container.DataItem, "thread_id") & "&p=" & DataBinder.Eval(Container.DataItem, "post_id") %>' Text="Edit" ID="Hyperlink1"></asp:HyperLink>

At the moment, this link appears in all posts (or datagrid rows) in a simplistic forum I coded years ago.

I can detect the user using the forum with the following code:


How do I show/hide the hyperlink on each post based on the servervariable?

So if I have 10 posts in a particular page, where 3 of those posts are by user x, how do I only show that hyperlink when user x is viewing that page, only on the posts which user x created?

Running an MVC web application.

Basically I have two twitter bootstrap files in ~/Content/bootstrap.css

When I run my application, the browser looks in : localhost:9999/%E2#$#/Content/bootstrap.css

I have a regular style sheet in the same directory which the browser finds.

My view links the the style sheet like this:

<link href="∼/Content/bootstrap.css" rel="stylesheet" type="text/css" />

I'm using this class to send some variables to an external application using post-method. You can check the full procedure ->HERE<-

/// <summary>
/// POST data and Redirect to the specified url using the specified page.
/// </summary>
/// <param name="page">The page which will be the referrer page.</param>
/// <param name="destinationUrl">The destination Url to which
/// the post and redirection is occuring.</param>
/// <param name="data">The data should be posted.</param>
/// <Author>Samer Abu Rabie</Author>

public static void RedirectAndPOST(Page page, string destinationUrl, 
                                   NameValueCollection data)
//Prepare the Posting form
string strForm = PreparePOSTForm(destinationUrl, data);
//Add a literal control the specified page holding 
//the Post Form, this is to submit the Posting form with the request.
page.Controls.Add(new LiteralControl(strForm));
        /// <summary>
        /// This method prepares an Html form which holds all data
        /// in hidden field in the addetion to form submitting script.
        /// </summary>
        /// <param name="url">The destination Url to which the post and redirection
        /// will occur, the Url can be in the same App or ouside the App.</param>
        /// <param name="data">A collection of data that
        /// will be posted to the destination Url.</param>
        /// <returns>Returns a string representation of the Posting form.</returns>
        /// <Author>Samer Abu Rabie</Author>

    private static String PreparePOSTForm(string url, NameValueCollection data)
        //Set a name for the form
        string formID = "PostForm";
        //Build the form using the specified data to be posted.
        StringBuilder strForm = new StringBuilder();
        strForm.Append("<form id=\"" + formID + "\" name=\"" + 
                       formID + "\" action=\"" + url + 
                       "\" method=\"POST\">");

        foreach (string key in data)
            strForm.Append("<input type=\"hidden\" name=\"" + key + 
                           "\" value=\"" + data[key] + "\">");

        //Build the JavaScript which will do the Posting operation.
        StringBuilder strScript = new StringBuilder();
        strScript.Append("<script language="'javascript'">");
        strScript.Append("var v" + formID + " = document." + 
                         formID + ";");
        strScript.Append("v" + formID + ".submit();");
        //Return the form and the script concatenated.
        //(The order is important, Form then JavaScript)
        return strForm.ToString() + strScript.ToString();

If I call the method from a simple WebForm everything works well, but if I try to do the same from a ContentPage inside a MasterPage nothing happens.

I tried to figure it out with very little success...any idea??

Using c# and silverlight

I want to display a current date in datepicker

Control Code

<sdk:DatePicker Name="cAccCreditDate"
                HorizontalAlignment="Left" VerticalAlignment="Center"  
 Width="120" Height="23" />

Tried in c#

cAccCreditDate.DisplayDate = DateTime.Now.Date; --date is not displaying
cAccCreditDate.DisplayDate = DateTime.Now; -- date is not displaying

How to display a date, need code help

So I'm working on an ASP.NET Web Forms application. I have :

`<asp:Panel ID="MyPanel" runat="server">'

Inside this panel I have other controls like Repeaters, textboxes etc, etc and on (!IsPostBack) I determine weather to show or not the entire panel by doing so:

 if (theClient.CType == "1")
     MyPanel.CssClass == "display-none"

Where display-none is defined like this:

.display-none {
    display: none;

However under some conditions I want to show this whole panel again and since I set the repeaters and stuff like that on (!IsPostBack) I would like to have all those set up. I'm not entirely sure how exactly those visibility properties are working, but what I need is the HTML markup to be rendered, the controls to be initialized with the correct data but just to have this hidden on the page but still active.

So having this in mind when the condition to show the panel is met I do this:

 MyPanel.CssClass = string.Empty;

But.. nothing happens. I'm not entirely sure, if I'm removing the style correctly, if this is the correct CSS style that I should be using for what I need to accomplish.

So how can I do this?

I have a .net program that lets the user select a chart from a dropdown and a data range then queries sql for the data to display the chart, everything is fine unless they pick a date range that would only return 1 value for that particular chart.

When this happens since there is only 1 point on the graph it does not display anything for line or area charts (it does work on bar and column).

i have thought about forcing the graph type to column if there is only 1 data point but was wondering if there was a setting i am missing that would allow a straight line on a line graph if there was only 1 datapoint.

well based on the idea of faking a 2nd point i came up with this that technically does what i want it to do.

this is called when there is only 1 point

 foreach (Series ser in mainChart.Series)