vendredi 31 mars 2017

Check if another action filter attribute is being used in action in MVC 5

I have few custom action filters like

public class CustomFilter:ActionFilterAttribute
{
  public override void OnActionExecuting(ActionExecutingContext filterContext)
  {
     //Some task
  }
}


public class CustomFilterNew:ActionFilterAttribute
{
  public override void OnActionExecuting(ActionExecutingContext filterContext)
  {
     //Some task
  }
}


In my action method

[CustomFilter]
[CustomFilterNew]
public ActionResult Index()
{
   return View();
}

Lets say CustomFilterNew exactly does opposite of CustomFilter.

In such case how to prevent one filter action from executing another filter action lets say CustomFilterNew should prohibit executing CustomFilter

jeudi 30 mars 2017

Fetching Data from Database and display in View by using MVC entity frame work

I am creating one application by using MVC entity framework. In my application user will login with email ID and will enter the task details and later user can able to view the data which saved. Unfortunately not able to display the data for particular user as all the users data coming into the view. Below is the code for the Controller

   public ActionResult TaskDetails(string td)
        {
            using (Data DE = new Data())
            {
                var email = Session["Email"].ToString();
                var displaydata = DE.TaskDetails.Where(u => u.ProjectID.ToString() == email).ToList();
                ViewBag.details = displaydata;

                return View();
            }
        }

Here email id is from one table and projectID from one table and by using primary key I am trying to get the data. But unfortunately all the users data is coming. This is code for my View @model MVC_Sample.Models.TaskDetail @{ Layout = null; }

@using (Html.BeginForm("TaskDetails", "Home", FormMethod.Post))
{
<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>TaskDetails</title>
</head>
<body>
    <div> 
        @foreach (var item in ViewBag.details)

        {
            <table id="t01">
                <tr>
                    <td>@item.ProjectID</td>
                    <td>@item.ProjectName</td>
                    <td>@item.StartDate</td>
                    <td>@item.EstimatedDate</td>
                    <td>@item.TaskDescription</td>
                </tr>

            </table>
        }
    </div>
</body>
</html>

Can any one help me to find where I did mistake.

mercredi 29 mars 2017

images not showing because relative path is not being converted to physical ASP MVC

I am storing image's relative path in my db and then when retrieved I passes it to my view via Model Binding method. When I am setting img's path to the path coming from db that relative path shows as it is in the html page instead of being converted into physical path. How can I force it to be converted to physical?

I tried Server.MapPath() in view but that doesn't help.

I wrote:

<img src=@Model.imgPath>

which is rendered as:

<img src="~/images/img.png">

in my browser.

Google Universal Analytics - Track download details

I am using the new Google Universal Analytics code and it tracks my page-views perfectly.

In addition to that I would like to track downloaded document details such as document name, UserID, etc.

When I googled, the suggestion was to include tracking code in OnClick method. But in my MVC application I am using ajax call and I am not using OnClick.

Is there any other option to track the same. Please let me know if there is a solution.

mardi 28 mars 2017

White space at top of page after converting .net project to use layouts

I recently changed my .net project to use master pages / layout pages. Now when my index page is rendered there is some space at the top of the page right before navbar.

I inspected that page in chrome, there is some empty quotes at the top of body, Removing those in the inspector solves the issue. but I am unable to understand where does that comes from? Here is my index.cshtml file.

@{
  Layout = "~/Views/Shared/_Layout.cshtml";
  ViewBag.Title = "my title";
}
<!--HERO IMAGE-->
<div>
    //code
</div>

@section additionalStyles{
   //adding external stylesheets
}

I am using render section in my index page to load some style sheets not useful in the rest of the pages. These are loaded up just before the ending tag of layout page like this:

@RenderSection("additionalStyles", required: false);

What possibly be causing that quotes?

Passing data from one form to another in asp.net mvc

I want to pass data from one form to another. I have a form of products and after submitting this form i want to add buttom to add posts to for this product, so i want to pass the Product ID to the other form.

this is my product.cs:

public partial class Produits
{

    public Produits()
    {
        this.Postes = new HashSet<Postes>();
    }

    public int idProduit { get; set; }
    public int idPole { get; set; }
    public Nullable<int> Reference { get; set; }
    public string DesignationProduit { get; set; }

    public virtual Pole Pole { get; set; }

    public virtual ICollection<Postes> Postes { get; set; }
}

This is my Post.cs:

public partial class Postes
{
    public int idPoste { get; set; }
    public Nullable<int> Numero { get; set; }
    public int idProduit { get; set; }
    public int idAtelier { get; set; }
    public string DesignationPoste { get; set; }

    public virtual Atelier Atelier { get; set; }
    public virtual Produits Produits { get; set; }
}

this is my Create.cshtml for the product:

@using (Html.BeginForm()) 
{
@Html.AntiForgeryToken()

<div class="form-horizontal">
    <h4>Produits</h4>
    <hr />
    @Html.ValidationSummary(true, "", new { @class = "text-danger" })


    <div class="form-group">
        @Html.LabelFor(model => model.idPole, "Pole", htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.DropDownList("idPole", null, htmlAttributes: new { @class = "form-control" })
            @Html.ValidationMessageFor(model => model.idPole, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.Reference, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.Reference, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.Reference, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.DesignationProduit, htmlAttributes: new {@class = "control-label col-md-2"})
        <div class="col-md-10">
            @Html.EditorFor(model => model.DesignationProduit, new {htmlAttributes = new {@class = "form-control"}})
            @Html.ValidationMessageFor(model => model.DesignationProduit, "", new {@class = "text-danger"})
        </div>
    </div>

    <div class="form-group">
        <div class="col-md-offset-2 col-md-10">
            <input type="submit" value="Create" class="btn btn-default" />
        </div>
    </div>
</div>
}

and this my Create.cshtml for the Post:

<form asp-controller="Postes" asp-action="Create" method="post" id="FormPs" role="form">
@Html.AntiForgeryToken()

<div class="form-horizontal">
    <h4>Postes</h4>
    <hr />
    @Html.ValidationSummary(true, "", new { @class = "text-danger" })

    <div class="form-group">
        @Html.LabelFor(model => model.idProduit, "Produit", htmlAttributes: new {@class = "control-label col-md-2"})
        <div class="col-md-10">
            @Html.DropDownList("idProduit", null, htmlAttributes: new {@class = "form-control"})
            @Html.ValidationMessageFor(model => model.idAtelier, "", new {@class = "text-danger"})
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.idAtelier, "Atelier", htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.DropDownList("idAtelier", null, htmlAttributes: new { @class = "form-control" })
            @Html.ValidationMessageFor(model => model.idAtelier, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.DesignationPoste, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.DesignationPoste, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.DesignationPoste, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        <div class="col-md-offset-2 col-md-10">
            <input type="submit" value="Create" class="btn btn-default" />
        </div>
    </div>
 </div>
 }

My Product controller:

 public ActionResult Create([Bind(Include = "idProduit,idPole,Reference,DesignationProduit")] Produits produits)
    {
        if (ModelState.IsValid)
        {
            db.Produits.Add(produits);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        ViewBag.idPole = new SelectList(db.Pole, "id", "designation", produits.idPole);
        return View(produits);
    }

My Post Controller:

 public ActionResult Create(Postes postes)
    {
        if (ModelState.IsValid)
        {
            db.Postes.Add(postes);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        ViewBag.idAtelier = new SelectList(db.Atelier, "id", "DesignationAtelier", postes.idAtelier);
        ViewBag.idProduit = new SelectList(db.Produits, "idProduit", "DesignationProduit", postes.idProduit);
        return View();
    }

I want to pass idProduit to the other form, Idproduit is an not manually added.

The model item passed into the dictionary is of type 'System.Data.Entity.DynamicProxies.Survey_D8

I have an error. It is

The model item passed into the dictionary is of type 'System.Data.Entity.DynamicProxies.Survey_D8226C5F5E348399740EDE08FDF0A956BDAD893915272C075AF983B0C50DA25E', but this dictionary requires a model item of type 'SurveySpaceProject.Models.User'.

I am taking a Survey from database but it need User. I tried some solutions from Stackoverflow but there is no way. Can you help me please? It is not a homework. It is my project and I am started asp.net 1 week ago.

My View

       public ActionResult FillSurvey(int id)
        {
            var s = SSPEntity.getDB().Surveys.FirstOrDefault(x => x.ID == id);
            return View(s);
        }

My FillSurvey Page :

       @model SurveySpaceProject.Models.Survey

     @{
    ViewBag.Title = "FillSurvey";
    }

    <h2>FillSurvey</h2>

    <div>
    <h4>Survey</h4>
    <hr />
    <dl class="dl-horizontal">
        <dt>
            @Html.DisplayNameFor(model => model.User.UserName)
        </dt>

        <dd>
            @Html.DisplayFor(model => model.User.UserName)
        </dd>

        <dt>
            @Html.DisplayNameFor(model => model.Title)
        </dt>

        <dd>
            @Html.DisplayFor(model => model.Title)
        </dd>

        <dt>
            @Html.DisplayNameFor(model => model.CreatedDate)
        </dt>

        <dd>
            @Html.DisplayFor(model => model.CreatedDate)
        </dd>

        <dt>
            @Html.DisplayNameFor(model => model.IsDeleted)
        </dt>

        <dd>
            @Html.DisplayFor(model => model.IsDeleted)
        </dd>

       </dl>
      </div>
       <p>
        @Html.ActionLink("Edit", "Edit", new { id = Model.ID }) |
        @Html.ActionLink("Back to List", "Index")
      </p>

And My Survey Model

            namespace SurveySpaceProject.Models
         {
    using System;
    using System.Collections.Generic;
    using System.ComponentModel.DataAnnotations;
    using System.ComponentModel.DataAnnotations.Schema;
    using System.Data.Entity.Spatial;

    public partial class Survey
    {
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
        public Survey()
        {
            SurveyAnswers = new HashSet<SurveyAnswer>();
            SurveyQuestions = new HashSet<SurveyQuestion>();
            //SurveyUsers = new HashSet<SurveyUser>();
        }

        public int ID { get; set; }

        public int UserID { get; set; }

        [Required]
        [StringLength(150)]
        public string Title { get; set; }

        [Column(TypeName = "date")]
        public DateTime? CreatedDate { get; set; }

        public bool IsDeleted { get; set; }

        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
        public virtual ICollection<SurveyAnswer> SurveyAnswers { get; set; }

        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
        public virtual ICollection<SurveyQuestion> SurveyQuestions { get; set; }

        public virtual User User { get; set; }

        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
        public virtual ICollection<SurveyUser> SurveyUsers { get; set; }
    }
}

Resource not found error in MVC when posting using beginform

The below code is not working properly as expected.

The controller have an action method

[HttpPost]
        public ActionResult LoginResult()
        {
            string name = Request.Form["name"];             
            return View("Dashboard");
        }
     public ActionResult Dashboard()
    {
        string strName = Request["username"].ToString();
        return View();
    }

and in view i have a form

 @using (Html.BeginForm("LoginResult", "Dashboard", FormMethod.Post))
    {  
     @Html.EditorFor(model =>model.username)
    <button type="button" id="ajax_method">submit Via AJAX</button>

    }

and im submitting this using a function

<script>       
    $(function () {
        $('#ajax_method').click(function (e) {
            e.preventDefault();    
            $.ajax({
                type: "POST",
                url: "Dashboard/LoginResult",                             //Your Action name in the DropDownListConstroller.cs
                data: "{'AJAXParameter1':'" + $('#username').val() + "'}",  //Parameter in this function, Is case sensitive and also type must be string
                contentType: "application/json; charset=utf-8",
                dataType: "json"

            }).done(function (data) {
                //Successfully pass to server and get response
                if (data.result = "OK") {
                    alert("submit successfully.");
                }
            }).fail(function (response) {
                if (response.status != 0) {
                    alert(response.status + " " + response.statusText);
                }
            });
        });

    });
</script>

but im getting 404 error while clicking the button.

Even I tried adding that routerspecifications in route config.

   routes.MapRoute(
            name: "login",
           url: "{controller}/{action}/{id}",
           defaults: new { controller = "Dashboard", action = "LoginResult", id = UrlParameter.Optional }
        );

and modified the cshtml again. But this is also not working.

 @using (Html.BeginForm("login", "Dashboard", FormMethod.Post))
    {  
     @Html.EditorFor(model =>model.username)
    <button type="button" id="ajax_method">submit Via AJAX</button>

    }

It may be a silly error but it spoil my day. Can anyone extend a hand to solve this issue.

samedi 25 mars 2017

WebGrid Search Exception - Error executing child request for handler

I want to make Search in WebGrid but it doesn't work.

I have 2 methods in Controller

 [HttpGet]
    public async Task<ActionResult> ICare()
    {.... return View(tuple);}
[HttpPost]
    public async Task<ActionResult> ICare(string Search)
    {.... return View(tuple);}

And in View I have

using (Html.BeginForm("ICare", "Communities"))
    {
        <div class="row">
            <div class="patientsearch">
                <div class="col-xs-6 col-md-3">
                    <div class="form-group">
                        <div class="input-group">
                            @Html.TextBox("Search", "", new {placeholder = "Search My Patients", @class = "form-control"})
                            <span class="input-group-btn">
                                <button type="submit" class="btn btn_green">Search</button>
                            </span>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        var grid = new WebGrid(Model.Item1, canSort: false, canPage: true, rowsPerPage: 10);
        <div class="table-responsive">
            @grid.GetHtml(
                mode: WebGridPagerModes.All,
                tableStyle: "table table-hover table-condensed",
                rowStyle: "table-row-clickable",
                headerStyle: "webgrid-header",
                footerStyle: "table-pager",
                columns:
                    grid.Columns(....

But it always throw an exception in Layout in this

 @{
                          Html.RenderAction("GetUserInfoForMenu", "Menu", new { Area = ""});
                        }

Error executing child request for handler 'System.Web.Mvc.HttpHandlerUtil+ServerExecuteHttpHandlerAsyncWrapper

vendredi 24 mars 2017

primary of one table set as foreign key in other table. how to retrieve value?

I have a table containing a primary key and that same primary key is used as a foreign key. How do I retrieve the value from the second table where there are multiple foreign keys with the same primary key in first table?

jeudi 23 mars 2017

MVC Model Validation Mechanism

When we create a model (for example using EF Code First) using Data Annotations we can use Required, 'Range', ...:

public class Employee
{
   public int EmpId { get; set; }

   [DisplayName("Employee Name")]
   [Required(ErrorMessage = "Employee Name is required")]
   [StringLength(100,MinimumLength=3)]
   public String EmpName { get; set; } 

   [Required(ErrorMessage = "Employee Address is required")] 
   [StringLength(300)]
   public string Address { get; set; } 

   [Required(ErrorMessage = "Salary is required")] 
   [Range(3000, 10000000,ErrorMessage = "Salary must be between 3000 and 10000000")]
   public int Salary{ get; set; } 
}

and when using Html.ValidationSummary and Html.ValidationMessage we can show error messages.

My question is when a View would load, in specific page load state those validations will get and convert to JavaScript codes and inject to page. I want to know this mechanism and convert those Data Annotations to JavaScript. I want to create custom validations for models and I want to simulate that behavior.

Thanks

Google Timeline chart, haxis position and start/end times for bars

I have created google timeline chart and would like to add the start and end time's to the bars and change the bottom xaxis to the top of the chart. But cant find anything for this from the timeline options. Is this possible somehow??

function ChartView(chartWidth, chartHeight, renderedTo, dataset, minTime, maxTime) {
var colors = [];
for (var i = 0; i < dataset.getNumberOfRows(); i++) {
    if (dataset.getValue(i, 0) == 'DataNotFound') {
        colors.push("#ffffdd");
    }
    else {
        colors.push(colorArray[dataset.getValue(i, 1)]);
    }
}
var options = {
    backgroundColor: '#ffd',
    enableInteractivity: false, // select, on/off events wont cause normal action i.e. bar color change
    hAxis: {
        format: 'HH:mm',
        minValue: minTime,
        maxValue: maxTime
    },
    height: chartHeight,
    width: chartWidth,
    colors: colors
};
var chart = new google.visualization.Timeline(document.getElementById(renderedTo));
var view = new google.visualization.DataView(dataset);
view.setColumns([0, 1, 2, 3]);
var container = document.getElementById(renderedTo);

google.visualization.events.addListener(chart, 'ready', function () {
    // set original color
    var bars = container.getElementsByTagName('rect');
    Array.prototype.forEach.call(bars, function (bar, index) {
        if (parseFloat(bar.getAttribute('x')) > 0 &&
            bar.getAttribute('fill') != "#e6e6c7" &&
            bar.getAttribute('fill') != "#ffffdd" &&
            index < (bars.length - 1)) {
                var textElem = bar.nextSibling;
                bars[index].setAttribute('fill', colorArray[textElem.innerHTML]);
        }
    });
});

google.visualization.events.addListener(chart, 'onmouseover', function (e) {
    // set original color
    var bars = container.getElementsByTagName('rect');
    Array.prototype.forEach.call(bars, function (bar, index) {
        if (parseFloat(bar.getAttribute('x')) > 0 &&
            bar.getAttribute('fill') != "#e6e6c7" &&
            bar.getAttribute('fill') != "#ffffdd" &&
            index < (bars.length - 1)) {
                var textElem = bar.nextSibling;
                if (textElem == null) {
                    bars[index].setAttribute('fill', "#ffffff");
                }
                else {
                    bars[index].setAttribute('fill', colorArray[textElem.innerHTML]);
                }
        }
    });
});

google.visualization.events.addListener(chart, 'onmouseout', function (e) {
    var bars = container.getElementsByTagName('rect');
    Array.prototype.forEach.call(bars, function (bar, index) {
        if (parseFloat(bar.getAttribute('x')) > 0 &&
            bar.getAttribute('fill') != "#e6e6c7" && // pohjaväri 1
            bar.getAttribute('fill') != "#ffffdd" && // pohjaväri 2
            index < (bars.length - 1)) {             // viimeinen aikajana bar
                var textElem = bar.nextSibling;
                if (textElem == null) {
                    bars[index].setAttribute('fill', "#ffffff");
                }
                else {
                    bars[index].setAttribute('fill', colorArray[textElem.innerHTML]);
                }
        }
    });
});
chart.draw(dataset, options);
}

mardi 21 mars 2017

Binding IEnumerable in ViewModel not working

I have a ViewModel - Customer. Within this there is an IEnumerable collection:

public class Tag
{
    public int TagNo{ get; set; }
    public DateTime CreatedDate { get; set; }
}

I output a list of tags to the page - along with the scalar customer information - using a foreach:

...output customer info....
<div class="col-md-9">
    @{
        foreach (var Tag in Model.Tags)
        {
            @Html.DisplayFor(x => Tag.TagNo);
            <br />
        }
    }
</div>

I am attempting to hide the tag list in the page for the model binder so on errors I don't need to hit the database again:

@{
    int[] tagArray = Model.Tags.Select(x => x.TagNo).ToArray();

    for (int i = 0; i < Model.Tags.Count(); i++)
    {
        @Html.Hidden("Tags[" + i + "]", tagArray[i])
    }
}

This outputs this:

<input id="Tags_0_" name="Tags[0]" type="hidden" value="21111111" />
etc

I have seen various questions on SO saying you can use an array (as above) in a certain format that the model binder will understand for binding lists - eg: Creating HiddenFor IEnumerable<String> in View

However, when the page has an error and I use the debugger to see what has been bound on the post, Although model.tags appears to have 3 elements - they are all empty.

I have also tried this:

@Html.Hidden("Tags[" + i + "].TagNo", tagArray[i])

But the Customer.Tags collection is empty after posting.

What am I doing wrong? How can I hide this list of tags in the page so that the model binder will see it?

How to make return to the current url to stay the same or should not postback after executing from an ActionResult method?

I have an actionresult which I used to call for saving something as shown below

  public async Task<ActionResult> GenerateData() 
    {
     //...my code to save something here

    return ???? // from here, after executing the statements above, 
// I want to return to the current url which should not post back and will just stay the same so that the user's inputs will remain. 

    }

In this case, my current url here that I want to stay the same is Home/Index. By looking at the code sample I shown above with its comment, how do I achieve this in order for me to return to the current url which will not postback or will stay the same after executing the statements before the return command? Thanks

lundi 20 mars 2017

Common function in razor view to generate drop down in multiple view pages

I have page which contains multiple dropdowns with option like

<option>1<option>
<option>2<option>
<option>3<option>

and

<option>-5<option>
<option>-6<option>
<option>-7<option>

so i have created in a function to generate dropdown options in razor view.

 @functions {
        public List<SelectListItem> GenerateDropDown(int startvalue, int endValue)
        {
            var dropDownList = new List<SelectListItem>();
            for (int i = startvalue; i <= endValue; i++)
            {
                string val = i.ToString();
                dropDownList.Add(new SelectListItem { Text = val, Value = val });
            }
            return dropDownList;
        }
}

and using like this

 @Html.DropDownListFor(m => m.xyz, GenerateDropDown(1, 10))
 @Html.DropDownListFor(m => m.Abc, GenerateDropDown(2, 20))

this work fine but i want use the same function in multiple pages with out code duplication i tried using helper method but no use can any one suggest me how to centralize GenerateDropDown function.

samedi 18 mars 2017

System.NullReferenceException: Object reference not set to an instance of an object.

 protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
    if (e.CommandName == "Delete")
    {
        try
        {
            int keyvalue = Convert.ToInt32(e.CommandArgument);
            //TextBox1.Text = keyvalue.ToString();
            con = new SqlConnection(str);
            con.Open();
            SqlCommand com = new SqlCommand("spDelete", con);
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.AddWithValue("@PatientId", keyvalue);

            cmd.ExecuteNonQuery();

            //da = new SqlDataAdapter(cmd);

            //GridView1.DataBind();
            con.Close();
        }
        catch (Exception ex)
        {
            Response.Write(ex);
        }


    }
}
trying to delete selected row but this error

System.NullReferenceException: Object reference not set to an instance of an object. at HospitalManagement.Edit.GridView1_RowCommand(Object sender, GridViewCommandEventArgs e) in C:\Users\sac\documents\visual studio 2015\Projects\HospitalManagement\HospitalManagement\Edit.aspx.cs:line 93

at cmd.commandType......... so help me

jeudi 16 mars 2017

Pass List as parameter to MVC controller

I try to do a thing I do everywhere in my code and for an unknown reason I can't do here.

I try to pass a list of object to my controller but I can't map my array into my list.

View :

var interventions = [
    {
        Id: 1,
        Title: 'Intervention 1',
        ToDoBefore: new Date(),
        PlannedDate: new Date()
    },
    {
        Id: 2,
        Title: 'Intervention 2',
        ToDoBefore: new Date(),
        PlannedDate: new Date()
    },
]

$.ajax({
    url: '/Home/AffectToSubcontractors',
    contentType: 'application/json; charset=utf-8',
    dataType: 'json',
    type: 'POST',
    data: JSON.stringify(interventions),
    success: function (result) {
        debugger;
    }
});

Controller :

    public PartialViewResult AffectToSubcontractors(List<SelectedInterventionsViewModel> interventions)
    {
        // Do something
    }

Model :

public class SelectedInterventionsViewModel
{
    public int Id { get; set; }

    public string Title { get; set; }

    public DateTime ToDoBefore { get; set; }

    public DateTime PlannedDate { get; set; }
}

What I miss ?

Asp.MVC custom handle error attribute does not work with Castle Windsor DI

I am working on an ASP.NET MVC application. I have used Castle Windsor for DI and have created a custom handler error attribute to handle errors in controllers.

I have created a custom windsor controller factory to use the DI. Now the issue is, with castle windsor, the custom error handler attribute code is never called, and I directly get the yellow screen of error.

When an error occurs in the controller, the error bubbles up to GetControllerInstance() method of WindsorControllerFactory, and then it never reaches the custom error handler of MVC.

Can anyone help me, how can I get the custom handle error attribute to work?

Please Note: Without the DI setup, the custom error handler works like charm

public override void OnException(ExceptionContext exceptionContext)
{
    var controllerName = (string)exceptionContext.RouteData.Values["controller"];
    var actionName = (string)exceptionContext.RouteData.Values["action"];
    var model = new HandleErrorInfo(exceptionContext.Exception, controllerName, actionName);

    exceptionContext.Result = new ViewResult
    {
        ViewName = View,
        MasterName = Master,
        ViewData = new ViewDataDictionary<HandleErrorInfo>(model),
        TempData = exceptionContext.Controller.TempData
    };

    exceptionContext.ExceptionHandled = true;
    exceptionContext.HttpContext.Response.Clear();
    exceptionContext.HttpContext.Response.StatusCode = (int)HttpStatusCode.InternalServerError;

    exceptionContext.HttpContext.Response.TrySkipIisCustomErrors = true;
}


public class WindsorControllerFactory : DefaultControllerFactory
{
    private readonly IKernel kernel;

    public WindsorControllerFactory(IKernel kernel)
    {
        this.kernel = kernel;
    }

    public override void ReleaseController(IController controller)
    {
        kernel.ReleaseComponent(controller);
    }

    protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType)
    {
        if (controllerType == null)
        {
            throw new HttpException(404, string.Format("The controller for path '{0}' could not be found.", requestContext.HttpContext.Request.Path));
        }
        return (IController)kernel.Resolve(controllerType);
    }
}

public class MvcApplication : System.Web.HttpApplication
{
    private static IWindsorContainer container;

    protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();
        RouteConfig.RegisterRoutes(RouteTable.Routes);
        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
        InitializeContainer();
    }

    private static void InitializeContainer()
    {
        container = new WindsorContainer()
            .Install(FromAssembly.This());
        var controllerFactory = new WindsorControllerFactory(container.Kernel);
        ControllerBuilder.Current.SetControllerFactory(controllerFactory);
    }

    protected void Application_End()
    {
        container.Dispose();
    }
}

mercredi 15 mars 2017

How to Pass parameter to partiaView with return View(.....)

Iam totaly new mvc programmer and have some problem with my code. From my controller calling/returning to a partial view like that..and its working: Below is my code:

return View("~/Views/Partials/_CarModels.cshtml, new RenderModel(carsrent) );

I want now to pass a parameter color to partialview, i have tryed this and i get Error

return View("~/Views/Partials/_CarModels.cshtml?color=red", new RenderModel(carsrent) );

What is worong ?

mardi 14 mars 2017

How can I save a List in ASP.NET

I would like to know how can I save a List (many column) instead of one column in ASP.NET, THANKS!!

    public ActionResult Audit(int? id)
    {
        var tQ = from t in db.TR.Include("SInfo")
                        where t.SId == id 
                        orderby t.SId, t.Tid
                        select t;

        var list = tQ.ToList();
        return View(list);
    }

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Audit(TrainingRecord list)
    {
        if (ModelState.IsValid)
        {
            db.Entry(list).State = System.Data.Entity.EntityState.Modified;
            db.SaveChanges();
            return RedirectToAction("Audit");
        }
        return View(list);
    }

I cannot save by this two contollers, is something missing or wrong in the controller or view?

Grid.Column if(else) two Grid.Column

I need to do something like this - if() - then grid.Column - else - then 1)grid.Column first and 2)grid.Column second

Now, I have this

grid.Column(header: "", format: @<text>@if (item.ListStatus != 1)
                                                   {
                                                       <button id='Resend' class='btn btn_green_resend'>Resend</button>
                                                   }
                                                   else
                                                   {
                                                   @*first column*@<a href=mailto: @item.Email class='btn btn-default' title='Send Email'><span class='glyphicon glyphicon-envelope text-primary' aria-hidden='true'></span></a>
                                                   @*second column*@<button type='button' title='Chat' class='btn btn-default' data-toggle='modal' data-target='#mdlConversation' data-interlocutorid=@item.UserId data-interlocutorname=@item.Name><span class='glyphicon glyphicon-comment text-primary' aria-hidden='true'></span></button>

            }
 </text>),

dimanche 12 mars 2017

what will happen if an asp.net project application is hosted in a hosting site got errors?

like in a localhost if errors occur a message will pop-up like data is null etc and you will just relaunch the application to be use again. what if it is already hosted in a hosting site what will happen to the application do a user will re upload again the application files in the hosting site? example of this error is like this http://ift.tt/2niTvt4 ( "can't upload picture in stack overflow just paste the URL link in the link bar to view" ) i'm just asking i'm very new in developing i'm just confused please dont be mad.

samedi 11 mars 2017

Url.Action to Html.Raw

I have this code om my View. And this is work good.

... onclick="location.href = '@Url.Action("Plan", "Care", new {Area = "HomeC"})'">

How Can I do the same code with Html.Raw? I tried this

...onclick= ' location.href = " + " ' " + Url.Action("Plan", "Care", new {Area = "HomeC"}) + " ' ' >" + "

With image all good, but link doesn't work. P.S. I added spaces that you can see where I put a single quotes

how to auto sum or automatically calculate when value is inputted in @html.editor

i have 5 property in the the table its score1 - score5 which are using @html.editor, how can i autosum all value inputted in the @html.editor which will be seen in my other property TotalScore? and it should automatically calculate without submiting or pressing the submit button.

vendredi 10 mars 2017

MVC: Trigger loading GIF when controller is processing

I got a loading gif feature in my ajax call. In all ajax call, I can trigger the loading gif.

But I want the loading gif to be triggered when I trigger a process in a controller too. The controller function is not being triggered by ajax call so my loading gif is not showing.

Is there any way I can trigger loading gif when controller is processing?

MVC 3 - Find script/method which fires PopUp

I know it is very basic question here but I am clueless. Since I am new to MVC I am unable to find out the script/method which fires PopUp menu.

In MVC3 application when I move my cursor over menu a PopUp list appears and I tried Google Chrome's Developers tool to find out how the PopUp appears but could not figure out.

Is there any tool or debugging mechanism available to find out which Script/Method fires Pop-Up screen.

DeserializeObject or Cast object from controller?

I have a Controller that deserialize the request in the following way;

public ActionResult ControlPartial() {
           Dictionary<string, object> modelState = (Dictionary<string, object>)new JavaScriptSerializer().DeserializeObject(Request.Params["ControlState"]); 
            SomeObject model = ControlModelFactory.CreateInstance(modelState );
            return PartialView("ControlPartial", model);
        }


 public static class ControlModelFactory{
         public static SomeObject CreateInstance(Dictionary<string, object> controlState){
           //Here is the Question! How I can deserialize or cast the controlState to SomeObject.
           return new SomeObject(){....};
             }
}

public class SomeObject{
 public int Width { get; set; }
 public Diccionari<string,Serie>{ get; set; }
}

public class Serie{
    public int ViewType { get; set; }
}

In my Request.Params["ControlState"] I have;

  • [0] {[Width, 0]} System.Collections.Generic.KeyValuePair
  • [1] {[Series,System.Collections.Generic.Dictionary`2[System.String,System.Object]]} System.Collections.Generic.KeyValuePair

     And Inside of the Series the following Value; 
     +        [0] {[serie1,System.Collections.Generic.Dictionary`2[System.String,System.Object]]} System.Collections.Generic.KeyValuePair<string,object>
                     +      [0] {[ViewType, 9]} System.Collections.Generic.KeyValuePair<string,object>
    
     +        [1] {[serie2,System.Collections.Generic.Dictionary`2[System.String,System.Object]]} System.Collections.Generic.KeyValuePair<string,object>
                     +      [1] {[ViewType, 11]}    System.Collections.Generic.KeyValuePair<string,object>
    
    

As you can see, from the client I get the JSON: {'Width':0, 'Series':{'serie1':{'ViewType':9},'serie2':{'ViewType':11}}}

What is the best method and how to convert from the controlstate to the object SomeObject? One problem is that I can not change the input parameter types.And I have to do the conversion inside CreateInstance.

mercredi 8 mars 2017

Date Time null in database

As my title above I got a table in my database that is DateTime datatype and it is null value. And I got this line of code that I am using but I don't know why that it is returning 12:00

string FitaCorIn1 = Convert.ToDateTime(req.FACorrectionIn1).ToString("hh:mm") == null ? "00:00" : Convert.ToDateTime(req.FAIn1).ToString("hh:mm");
string FitaCorOut1 = Convert.ToDateTime(req.FACorrectionOut1).ToString("hh:mm") == null ? "00:00" : Convert.ToDateTime(req.FAIn1).ToString("hh:mm");

So as you can see in my code If the value of datetime is null I want to display 00:00 and if it is not null it will display the current value.

NOTE

12 Hours Format

mardi 7 mars 2017

Mapped Folder Not Working On Publish

I am creating an web application. I have to show one attachment in a button click.The attachment file resides on another server which is in the same network. when i make the coding its works well in my development machine, but when i deploy it does not work.

i am deploying the application in 192.168.a.xyz server and the mapped folder is in 192.168.a.ijk.

i have used the below code which works well in the development machine which is also in the same network.

public ActionResult GetCorporateInvoiceCopy(string attachId)
        {
            if (attachId.Length > 0)
            {
                try
                {
                    string FileExtension = ".pdf";
                    string csvPath = "";
                    string inv = attachId;
                    csvPath = @"\\192.168.a.ijk\\Attached_Files\" + Path.GetFileName(inv.ToString() + FileExtension );
                    return File(csvPath, FileExtension);
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
            else
            {
                return null;
            }
        }

Appreciate if anybody can help!

Capturing parts of MVC Views

I am capturing parts of MVC views like so:

<% using(Html.BeginScriptWrapper()) { %>
<script type="text/javascript">
    alert("Test : <%: DateTime.Now %>");
</script>
<% } %>

The code of HtmlHelper extension:

public static class HelperScriptWrapper
{
  public static IDisposable BeginScriptWrapper(this HtmlHelper anHtml)
  {
    return new ScriptWrapper(anHtml);
  }

  class ScriptWrapper : IDisposable
  {
    private HtmlHelper fHtml;
    private TextWriter fOldWriter;
    private StringWriter fNewWriter;

    private TextWriter ReplaceInnerWriter(TextWriter aReplacement)
    {
      TextWriter writer = fHtml.ViewContext.HttpContext.Response.Output;
      PropertyInfo propInfo = writer.GetType().GetProperty("InnerWriter",
        System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);

      TextWriter oldWriter = propInfo.GetValue(writer, null) as TextWriter;
      propInfo.SetValue(writer, aReplacement, null);

      return oldWriter;
    }

    public ScriptWrapper(HtmlHelper anHtml)
    {
      fHtml = anHtml;
      fNewWriter = new StringWriter();
      fOldWriter = ReplaceInnerWriter(fNewWriter);
    }

    public void Dispose()
    {
      ReplaceInnerWriter(fOldWriter);
      string result = fNewWriter.GetStringBuilder().ToString();
      // store result to use later
    }
  }
}

Reflection is used to replace InnerWriter above with my StringWriter.

Is there a proper (ASP.NET MVC by-design) way to do this without reflection? That is to redirect content that goes to Response.Output in the middle of the view.

Not showing the id in the screen when hovering

I am using leaflet and mapbox and I use the function to print the id nuber on the screen when hovering over the line in the map.

geojson = L.geoJson(lines, {
    style: style,
    onEachFeature: onEachFeature
}).addTo(map);

var info = L.control();

info.onAdd = function (map) {
    this._div = L.DomUtil.create('div', 'info'); // create a div with a class "info"
    this.update();
    return this._div;
};


info.update = function (props) {
    this._div.innerHTML = '<h4><b>Links<b></h4>' +  (props ?
        '<b>Link' + props.id + '</b><br />'  
        : 'Hover over a link');


};

info.addTo(map);

The way I draw the line is by the following geoJSON file

var lines = {
    "type": "FeatureCollection",
    "features": [{
        "type": "LineString",
        "coordinates": [
            [103.85, 1.28992],
            [103.89, 1.294],
            [103.83, 1.216]
        ],
        "properties": { "id": "1" }
    }, {
        "type": "LineString",
        "properties": { "id": "2" },
        "coordinates": [
            [103.5, 1.292],
            [103.9, 1.4],
            [103.3, 1.21]
        ]
    }, {
        "type": "LineString",
        "properties": { "id": "3" },
        "coordinates": [
            [103.6, 1.291],
            [103.6, 1.39],
            [103.3, 1.29]
        ]
    }]
};

but when i hover over the line it shows "undefined" instead of showing the id.Any help is appreciated

Calculate center coordinates, zoom, and stops of the layer dynamically

Below is my code to display a base map, set center coordinates and zoom level to show Ghana in view-port and also style/ color the ghana map for NDVI property of my source layer (mapbox hosted tileset) ghanaNDVILayer.

 mapID='myMapID';
    mapboxgl.accessToken = 'accessToken';

    var map = new mapboxgl.Map({
        container: 'map',
        style: 'mapbox://styles/mapbox/streets-v9',
        center: [-1.41, 6.32],
        zoom: 5
    });

    map.on('load', function () {
        map.addLayer({
            'id': 'main',
            'type': 'fill',
            'layout': {},
            'paint': {
                'fill-color': {
                  property: 'NDVI',
                    stops: [
                        [0, '#F2F12D'],
                        [1, '#EED322'],
                        [2, '#E6B71E'],
                        [3, '#DA9C20'],
                        [4, '#CA8323'],
                        [5, '#B86B25'],
                        [6, '#A25626'],
                        [7, '#8B4225'],
                        [8, '#723122']
                    ]
                },
                'fill-opacity': 0.8
            },
            'source': {
                'type': 'vector',
                'url': 'mapbox://' + mapID
            },
           "source-layer": "ghanaNDVILayer",
        });
    });

Now if you see in above code I've hard coded the center coordinates, zoom level and stops array which is typical for this Ghana NDVI trends example.

Now, this approach is fine when I am dealing with only one data source (in this case ghana data source) but I can't hard code these values as my data source could change and could be any region of the world and the property could also be anything other than NDVI.

I am using mapbox hosted tilesets as the data source, but I also have the original geoJson data source on my server.

Is there any way in Mapbox to calculate center, zoom and stops dynamically depending on the source we are loading?

The other approach I thought is to pass the tileset source Id to my server and locate the original geoJSON and using that calculate the center, zoom and stops on the server and then pass these values to my client and then render the map in the js.

Let me know what is the best way to calculate these values dynamically.

Mapbox data with google sheets

I am working to develop a crowdsourcing website that takes input from google forms and displays this information on a map. I am working with mapbox and am looking for a way to get the data points in my google spreadsheet (with lat/long info) to automatically show up on the map. Any tips would be appreciated, thanks!

Drawing annotations over mapbox map

I am using Mapbox as my mapping library. I am trying to add a functionality where after the map has been rendered completely, the user can draw an annotation and add a comment for it (see image). Now, these annotation details (drawn line coordinates and message) should be saved into my GeoJSON, so that next time when the user reloads the map, it should show the same annotation.

Now I didn't find native support in mapbox for annotation. So not sure how to implement this.

Is there any way to draw annotations over the map after the map is rendered?

enter image description here

lundi 6 mars 2017

jquery 1.4.2 and chrome.. detecting a check box is checked....How?

So for reasons beyond my control, I'm using jquery 1.4.2 and chrome..

I'm having a ludicrous amount of trouble trying to get detecting a check box is checked....working...

Here is what I have...

HTMl generated by asp.net Mvc3

<input type="checkbox" name="criteriaVm.WasApproved" id="criteriaVm.WasApproved">

Various versions I've tried

            var ob = $("#criteriaVm.WasApproved");// is valid
            var chk = ob.attr('checked'); // undefined
            //chk = ob.prop('checked');//crash
            //chk = ob.get(0).checked;//crash
            //chk = ob.get(0).is(":checked");//crash

I've tried others before I started keeping track to make sure I wasn't just going in circles...

Does anyone know what version works on the old school jquery i'm, stuck with?

samedi 4 mars 2017

ASP.NET MVC how can i display users information from active directory but not in the list of principal

ASP.NET MVC, how can i display users information from active directory but not in the list of principal ??

For example, I want to display users mobile number but mobile attribute is not in the list of user principal.

Also I would like to set a pin code for all users i asked someone in the team to create the field in the ACTIVE DIRECTORY as pin code. so basically it is a new field will be created. How can i add it also to the list of user principal and allow users to set it? please Note that i'm new to ASP.NET MVC

Thanks

jeudi 2 mars 2017

i'm having trouble putting set of value to the actionlink using mvc

    @Html.ActionLink("LecturePage", "Lecture", new { id=item.LectureId })

i want to set some values in the item.lectureId, like set the value of item.lectureId to 1 or 2 or 3 or etc. How can i do it? please do help me.

mercredi 1 mars 2017

How to change dropdown list to multiselect dropdown list

I have dynamically populated dropdown list, which I have tried to change to support multiselection. I have tried change the Html.DropDownList to ListBox, SelectList to MultiSelectList and html attribute: new { multiple = "multiple" }. But just cant get this to work. Can you help me?

Dynamically populate the dropdownlist:

$.post('<%= Url.Action("Groups", "Units") %>', { unitId: $('#UnitId').val() }, function (data) {
    $('#Groups').html('<option value="null">Select group</option>');
    $.each(data.list, function (index, element) {
        $('#Groups').append('<option value="' + element.Id + '">' + element.Name + '</option>');
        $('#li-group > .fade').hide();
    });
});

Show the dropdown list:

<!-- Group dropdown list -->
<li id="li-group">
    <div class="fade"></div>
    <%= @Html.DropDownList("Groups", new SelectList (new List<Object> { new { value = "null", text = "Select group" } }, "value", "text" )) %>
</li>

Send the selection to controller:

$('#page-content > .wrapper').load(url, { Group: $('#Groups').val() });

public ActionResult GroupSelection(string Group)

Tried to change this to:

$('#page-content > .wrapper').load(url, { Group: $('#Groups option:selected').val() });

public ActionResult GroupSelection(List<string> Group)

or

public ActionResult GroupSelection(string[] Group)

Capturing parts of MVC Views

I am capturing parts of MVC views like so:

<% using(Html.BeginScriptWrapper()) { %>
<script type="text/javascript">
    alert("Test : <%: DateTime.Now %>");
</script>
<% } %>

The code of HtmlHelper extension:

public static class HelperScriptWrapper
{
  public static IDisposable BeginScriptWrapper(this HtmlHelper anHtml)
  {
    return new ScriptWrapper(anHtml);
  }

  class ScriptWrapper : IDisposable
  {
    private HtmlHelper fHtml;
    private TextWriter fOldWriter;
    private StringWriter fNewWriter;

    private TextWriter ReplaceInnerWriter(TextWriter aReplacement)
    {
      TextWriter writer = fHtml.ViewContext.HttpContext.Response.Output;
      PropertyInfo propInfo = writer.GetType().GetProperty("InnerWriter",
        System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);

      TextWriter oldWriter = propInfo.GetValue(writer, null) as TextWriter;
      propInfo.SetValue(writer, aReplacement, null);

      return oldWriter;
    }

    public ScriptWrapper(HtmlHelper anHtml)
    {
      fHtml = anHtml;
      fNewWriter = new StringWriter();
      fOldWriter = ReplaceInnerWriter(fNewWriter);
    }

    public void Dispose()
    {
      ReplaceInnerWriter(fOldWriter);
      string result = fNewWriter.GetStringBuilder().ToString();
      // store result to use later
    }
  }
}

Reflection is used to replace InnerWriter above with my StringWriter.

Is there a proper (ASP.NET MVC by-design) way to do this without reflection?

Do I have to learn asp.net before learning mvc

I am planning to learn mvc but i'm just wondering should i learn asp.net first ? Will it be easy to learn mvc after learning asp.net ?