dimanche 31 mai 2015

C#(asp net mvc) -How to remove escape characters from string in controller or jquery?

When I receive a string which has a special character in controller from an Ajax call, I see the following behaviour

string actualContent ="abc\efg";

The \ in the content is received as

string contentReceived ="abc\\efg";

What is the best way to remove the escaping character \ ? Either in controller while receiving this string or in jquery while post processing this.

How to run ASP.NET MVC project inside another ASP.NET MVC project

Let's say I have a MVC project where there is root folder MVC2 and. Now, I want another MVC project to that MVC2 folder and serve it.

Below url should serve MVC2 project which is just a folder inside the root project. Root project is also MVC.

  • currentSite.com -> current mvc app
  • http://ift.tt/1AEmRqG -> should run nested mvc app.

I think there should be a webconfig setting which should make it work.

Thank you in advance. Any answer will be dearly appreciated.

Is it possible? and if it is , is it possible to interact with each other.

How to add drop-down list instead of a textfield in Web API

I will put a "Choose Civil Status" parameter inside a POST method in my Swagger-UI, so instead of a text fields I wanted it to be a drop down list, I'm using MVC 3, Can anyone explain how can I do that?

here is my sample code..

 [HttpPost]
        public string Generate(string id, Salutation Salutation)
        {
             //code here
        }

vendredi 29 mai 2015

Exporting a hyperlink in Pivot Grid

I currently have a Pivot Grid that exports both a GridView and PivotGrid. The GridView export correctly creates hyperlinks for users. However, the PivotGrid export does not. My question is, is there a way to export the hyperlink so that it is still a hyperlink?

Below is my code for what I have in my Controller to do the export.

public ActionResult ExportPivotGrid()
    {
        //A fresh copy of data
        Session["IPDReportsData"] = IPDReport.GetReportData(Session["AdHocDataSource"].ToString(),
            SCCView.Classes.Helper.OfficeId);

        var pivotGridSettings = new PivotGridSettings();
        pivotGridSettings.Name = "ExportPivotGrid";
        pivotGridSettings.BeforePerformDataSelect = (s, e) =>
        {
            MVCxPivotGrid PivotGrid = s as MVCxPivotGrid;
            //Get the current layout of the Pivot Grid
            string layout = (string)(Session["IPDCurrentPivGridLayout"]);
            PivotGrid.LoadLayoutFromString(layout, DevExpress.Web.ASPxPivotGrid.PivotGridWebOptionsLayout.DefaultLayout);
        };

        XlsxExportOptionsEx xopt = new XlsxExportOptionsEx();
        xopt.AllowHyperLinks = DefaultBoolean.True;
        xopt.ExportHyperlinks = true;
        xopt.TextExportMode = TextExportMode.Text;
        xopt.ExportType = DevExpress.Export.ExportType.WYSIWYG;

        return PivotGridExtension.ExportToXlsx(pivotGridSettings,
                    Session["IPDReportsData"], true, xopt);

    }

I do have this working within the Pivot Grid for the page displayed, but only by using the FieldValueDisplayText method in the settings of the Pivot Grid. However, when I tried to apply this to my export, the export never loaded.

Any help would be appreciated.

Web Grid with dynamically created model in asp.net mvc3

I am builing an ASP.Net mvc3 website which comprises of a series of forms all built on top of different models. Once the user fills up each form a "Confirm" page is shown which will show the fields of the form filled along with data in grid format to the user. I am facing difficulty in showing the Confirm view as the model keeps on changing for each form. Following is my Controller method for Confirm:

public ActionResult Confirm(string ReqType)
        {
            var result = new List<dynamic>();
            if (ReqType == "AcctDesc")
            {
                DbContext.AcctDescDbContext objAcctDescDbContext = new DbContext.AcctDescDbContext();
                Models.AccountDesc objAcctDesc = objAcctDescDbContext.GetLatestRecord();
                ViewData["AcctDesc"] = objAcctDesc;
                ViewBag.ObjectModel = objAcctDesc;


                    var obj = (IDictionary<string, object>)new ExpandoObject();

                    obj.Add("Req_Name",objAcctDesc.Req_Name);
                    obj.Add("Req_Date",objAcctDesc.Req_Date);
                    obj.Add("ApprovalGroup",objAcctDesc.ApprovalGroup);
                    obj.Add("Account",objAcctDesc.AC_proposed);
                    obj.Add("Reason",objAcctDesc.AC_definition);
                    obj.Add("Language",objAcctDesc.AC_language);
                    obj.Add("CurrentShortText", objAcctDesc.AC_Currentshorttext);
                    obj.Add("CurrentLongText", objAcctDesc.AC_CurrentLongtext);
                    obj.Add("NewShortText", objAcctDesc.AC_Newshorttext);
                    obj.Add("NewLongText", objAcctDesc.AC_Newlongtext);

                    result.Add(obj);
                }
            ViewBag.result = result;
            return View();

            }

Following is the Confirm view:

@{
    ViewBag.Title = "Confirm";
    Layout = "~/Views/Shared/_LayoutMasterDataForms.cshtml";
}

<div>

@{
    var grid = new WebGrid(ViewBag.result);  

    }

    @using (Html.BeginForm())
{   
    <div id="grid"> 
        @grid.GetHtml() 
    </div> 
}
</div>

The problem is the gird is not getting rendered in the Confirm page-blank Html is coming up, what is the issue here? Please help.

jeudi 28 mai 2015

How can I add new method in Swagger UI?

I'm new to Swagger API so does in ASP.Net, I would like to know if how can I add new HTTP methods(e.g. GET, POST, PUT, DELETE) on the UI. It only contains 6 methods as a default. I would like to add like another GET method. So, any help?

Controller

using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;

namespace DemoSwagger.Controllers
{
    public class ValuesController : ApiController
    {
        // GET api/values
        public IEnumerable<string> Get()
        {
            return new string[] { "Cat", "Dog", "Bear" };
        }

        // GET api/values/5
        public string Get(int id, string sm, string BCID)
        {
            if (id == 1)
            {
                return "Cat";
            }
            else if (id == 2)
            {
                return "Dog";
            }
            else if (id == 3)
            {
                return "Bear";
            }
            else
            {
                return "Out of Range";
            }    
        }

        // POST api/values
        public void Post([FromBody]string value)
        {


        }

        // PUT api/values/5
        public void Put(int id, [FromBody]string value)
        {

        }

        // DELETE api/values/5
        public void Delete(int id)
        {

        }    
    }
}

what is the best way to do validations in MVC

Can someone please guide me how to do validations in MVC they may be different ways can you please list down the ways to do it.

thank you

mercredi 27 mai 2015

ASP.NET - Iterate through dynamic properties from IList

I'm trying to create an Attribute Validator that, given a list, must ensure that the list have at least one element.

So, I have this for the moment

public override bool IsValid(object value)
{
    var list = value as IList;

    if (list != null)
        return list.Count >= 1;

    return false;
}

My problem is that, I can receive a list with more than one element, but the properties of all these elements are null, so I need to iterate over each property to check them. And I'm not really sure how can I achieve that without knowing the name of the property.

How to add a text box and a column to save text in it dynamically in ASP.NET MVC 3 application

I have to add a button which when clicked creates a new text box where I can add some text and save it in database. For example- I click button thrice it will create 3 text boxes and 3 new columns in database to save them. Application is in ASP.NET MVC 3 and Entity Framework 4.3.1. Is it possible to do that using EF as it maps to static classes?

Kendo dropdownlist binding event inside grid client template

Am trying to add a dropdown inside the kendo grid. An di need to add it inside the clienttemplate instead of editortemplates as i need the whole grid to be in edit mode on loading itself.

And this is the way i did it.

.ClientTemplate("<input class='pUomDdl' #= UOMCodeEnabled ? disabled='disabled' : '' # value='#= UOMCode #' data-uomCode='#= UOMCode #' data-role='dropdownlist' data-source='UOMList' data-text-field='Text' data-value-field='Value' change='onUOMchange'/>");

Now my problem is the change event is not at all getting invoked. Dropdown is asking me for the event but when i add it to script tag it's not at all getting called.

Any clue??

mardi 26 mai 2015

why i am getting error?? asp c#

Why i am getting error when my syntax is

protected void Button1_Click(object sender, EventArgs e)
    {
       if(TextBox1.Text.length<0)
       {

           Label1.Text = "Enter emoloyee name"; 

       } 

       else
       {


            try
        {
            con.Open();
            SqlDataAdapter da = new SqlDataAdapter("select * from employee where employee_name like '" + TextBox1.Text + "%'", con);
            DataSet ds = new DataSet();
            da.Fill(ds);
            GridView1.DataSource = ds;
            GridView1.DataBind();
            con.Close();

        }
        catch(Exception ex)
        {

            Response.Write("error is:" + ex);
        }

I am not getting error when i am using this syntax

protected void Button1_Click(object sender, EventArgs e)
{
   if(TextBox1.Text == "")
   {

       Label1.Text = "Enter emoloyee name"; 

   } 

   else
   {


        try
    {
        con.Open();
        SqlDataAdapter da = new SqlDataAdapter("select * from employee where employee_name like '" + TextBox1.Text + "%'", con);
        DataSet ds = new DataSet();
        da.Fill(ds);
        GridView1.DataSource = ds;
        GridView1.DataBind();
        con.Close();

    }
    catch(Exception ex)
    {

        Response.Write("error is:" + ex);
    }

Can any one explain why this is happenning both textbox.text syntax signifies emplty box but the former syntax is giving error while the latter onle is working fine for me.

lundi 25 mai 2015

How to Make MultiSelect Dropdown List in Mvc

How to Make MultiSelect Dropdown List in Mvc .Please Give Me a Full Sample Code its Urgent For Me.

Change the position of html code of popup of jquery-ui-1.11.4

I use jquery-ui-1.11.4 dialog to show submit form but the html code of popup is putted after all other tag in by default, so this code is not in tag. That the reason why the input values do not post to controller in MVC3. I want to change the position of this html code into tag. How can I do this?

Dai Nguyen Quang, THP group.

Call Controller methods after rows reordered in sortable rows

I want to do the row reorder functionality in jqgrid.

I have referred a sortable rows example given by trirand website,I can move rows up and down,

do we have any methods to get the row reordered and call ajax events for the moved row?

This is my grid:

jQuery(document).ready(function () {
    var pageWidth = $(window).width();
    var lastSel;
    $("#sortrows").setGridWidth(pageWidth);
    $('#sortrows').jqGrid('GridUnload');
    jQuery("#sortrows").jqGrid({            
        datatype: "local",
        mtype: "GET",
        hoverrows: false,
        jsonReader: { repeatitems: false, id: "Index" },
        ajaxGridOptions: { timeout: 30000 },
        colNames: PricelistHeaderColName,
        colModel: PricelistHeaderModel,
        id: 'Index',
        localReader: { id: 'Index' },
        prmNames: { id: "Index" },
        rowNum: 10,            
        rowList: [10, 20, 30],
        hidegrid: false,
        rownumbers: true,
        viewrecords: true,
        height: 'auto',
        width: pageWidth,
        scrollOffset: 0,
        gridview: true,
        autowidth:true,
        shrinkToFit: true,
        pager: '#psortrows',
        sortname: 'Description',
        autoencode: true,
        loadonce: true,
        ignoreCase: true,
        multiselect: false,
        viewrecords: true,
        sortorder: "asc",
        caption: "PriceList Headers",
        editurl: "../Header/Save",            

    });

    $('#sortrows').jqGrid('setLabel', 'Description', "Description", { 'text-align': 'left' });

    jQuery("#sortrows").jqGrid('navGrid', '#psortrows',
        {
            edit: false,
            add: false,
            del: false,

        });


    jQuery("#sortrows").jqGrid('inlineNav', '#psortrows',
        {
            add: true,
            addtext: "Add",
            addicon: "ui-icon-plus",
            edit: true,
            editicon: "ui-icon-pencil",
            edittext: "Edit",
            save: true,
            saveicon: "ui-icon-disk",
            savetext:"Save",
            cancel: true,
            cancelicon: "ui-icon-cancel",
            canceltext: "Cancel",
            search: true,
            searchtext: "Seaech",
            del: true,
            deltext: "Delete",
            delicon : "ui-icon-delete",

            // additional parameters below:
            editParams: inlineEditOptions,
            addParams: { addRowParams: inlineAddOptions }                

        });

    jQuery("#sortrows").jqGrid('sortableRows', { items: '.jqgrow:not(.unsortable)' });

    $('#sortrows').jqGrid('filterToolbar', { searchOnEnter: false, enableClear: false, defaultSearch: "cn", stringResult: true });

    //var myData = $('#sortrows').jqGrid('getDataIDs');        
    for (var i = 0; i < myData.length; i++) {            
        //jQuery("#sortrows").addRowData(myData[i].Code, myData[i]);
        $("#sortrows").jqGrid('addRowData', i + 1, myData[i]);

    }
    var recordCount = $("#sortrows").jqGrid('getGridParam', 'reccount');
    console.log(recordCount);

});

I need to call controller actions to save database changes after the row is reordered..I cant found the solution. Kindly help me on this............

Do not want to add angular.min.js reference in every cshhtml page?

Do not want to add angular.min.js reference in every cshhtml page?

I have tried to add all references into _Layout.cshtml page but it is not working properly :(

Any clue or suggestions how to add references ?

dimanche 24 mai 2015

How to hide Query string parameter in URL

I have a Telerik grid in which I am using client templates for edit/delete actions for each record. So for the edit/delete action I need to pass the id of that record along with the URL, here in this case I am afraid about some security issues. I am looking for a way to hide the query string parameter here to overcome this issues.

I am aware about encryption of parameter and currently I am using that. But i want to completely hide the query string parameter. I can't use session/ViewBag here since I can't set the session value for each record at the time of button click and access it in controller.

Any help is appreciated. Thanks in advance. my Controller and View codes are the following

View

@model IEnumerable<Data.Models.MyViewModel>
@{
    Volunteer.Data.User currentUser = (Data.User)Session["CurrentUser"];
}
<div id="myDivId">
    <p style="clear:none;">
        @Html.ActionLink("Add", "Create", "MyController", new { area = "", ID = ViewBag.MyDataID }, new { @class = "aMyClass" })
    </p>
    @{
        Html.Telerik().Grid<MyViewModel>().Name("MyGrid")
            .Columns(col =>
            {
                col.Bound(c => c.FirstName).Width("120px");
                col.Bound(c => c.LastName).Width("80px");
                col.Bound(c => c.Designation).Width("80px");
                col.Bound(c => c.Company).Width("80px");
                col.Bound(c => c.Married).Filterable(false).ClientTemplate(
                    "<input type='checkbox'" + "<#= Married?\"checked\":\"\" #>" + " OnClick='return false' />"
                    ).Width("40px");               
                if (currentUser.AdminRole == true || currentUser.Manager == true || currentUser.StaffRole == true)
                {
                    col.Bound(c => c.EmployeeID).Sortable(false).ClientTemplate(
                                        "<a href='" + Url.Content("~/MyController/Edit/") + "<#= EmployeeID #>' title='Edit Employee Details' class='edit'>Edit</a>" +
                                        "<a href='" + Url.Content("~/MyController/Delete/") + "<#= EmployeeID #>' title='Delete Employee Details' class='delete'>Delete</a>"
                    ).Title("Action").Width("75px");
                }
                else
                {
                    col.Bound(c => c.EmployeeID).Sortable(false).ClientTemplate(
                                        "<a href='" + Url.Content("~/MyController/Details/") + "<#= EmployeeID #>' title='Associated Party Details' class='details'>Details</a>"
                    ).Title("Action").Width("75px");
                }
            })

        .DataBinding(dataBinding => dataBinding.Ajax().Select("_GetEmployeeList", "MyController", new { id = "MyDataID" }))
        .Pageable()
        .Sortable()        
        .Render();
    }
</div>

Controller

public ActionResult Edit(int id)//Want to pass this id without using Query string parameter
{
    User user = (User)Session["CurrentUser"];

    Employee employee = db.Employees.Single(c => c.EmployeeID == id);
    //some code
    return View(employee);
}

[HttpPost]
public ActionResult Edit(Employee employee)
{
    User user = (User)Session["CurrentUser"];

    if (ModelState.IsValid)
    {
        db.Employees.Attach(employee);
        db.ObjectStateManager.ChangeObjectState(Employees, EntityState.Modified);
        db.SaveChanges();
        return RedirectToAction("Index");
    }
    Employee employee = db.Employees.Single(c => c.EmployeeID == id);
    //some code
    return View(employee);
}

jQuery AJAX in MVC3

I am working on a database viewer in MVC C#, and there is a div that contains connectivity details. This is the complete view (the third function is the one of interest):

<script>
   function moveConfigureConnectionDiv(){
            var windowHeight = jQuery(window).height();
            var windowWidth = jQuery(window).width();
            var newLoaderTop = (windowHeight*.8 - 250) / 2;
            var newLoaderLeft = (windowWidth - 185) / 2;
            document.getElementById('configureConnectionDiv').style.top = newLoaderTop + "px";
            document.getElementById('configureConnectionDiv').style.left = newLoaderLeft + "px";}
   function openConfigureConnectionDiv() {
            moveConfigureConnectionDiv();
            document.getElementById("configureConnectionDiv").style.display = "block";}
            $(window).resize(function(){
                      moveConfigureConnectionDiv();});
   function setConfigureConnection(){
       alert('asdf');
            $.ajax({url         : '@Url.Action("SetConfigureConnection")',
                    dataType    : "json",
                    type        : "POST",
                    contentType : 'application/json; charset=utf-8',
                    cache       : false,
                    data        : "{server: '"   + $("#ServerTB"  ).val() + "', " +
                                   "db: '"       + $("#DatabaseTB").val() + "', " +
                                   "userID: '"   + $("#UserIDTB"  ).val() + "', " +
                                   "password: '" + $("#PasswordTB").val() + "'}",
                    success     : function(data){
                                           if(data.success){}},
                    error       : function(xhr){}});}
   </script>
<form runat="server">
<div id="tables">
     <div id="tablesTitle" class="tableItem">Tables in Database</div>
     </div>
<div id="queryConfigure">
     <div id="queryBar">Query: @Html.TextBox("queryTextBox", null, new{style="width:80%;margin:3px"})</div>
     <div class="floatRight paddingRight10" style="margin-top:4px;color:blue">
          <div id="openConfigureConnectionDiv" onclick="openConfigureConnectionDiv()">Configure Connection</div>
           </div>
      </div>
 <div id="configureConnectionDiv">
      <table>
            <tr>
               <td>Server</td>
               <td>@Html.TextBox("ServerTB")</td>
               </tr>
            <tr>
               <td>Database</td>
               <td>@Html.TextBox("DatabaseTB")</td>
               </tr>
            <tr>
               <td>User ID</td>
               <td>@Html.TextBox("UserIDTB")</td>
               </tr>
            <tr>
               <td>Password</td>
               <td>@Html.TextBox("PasswordTB")</td>
               </tr>
            <tr>
               <td colspan="2">
                   <input type="button" 
                          id ="configureConnectionButton" 
                          class="width100" 
                          style="height:40px" 
                          value="Set"
                          onclick ="setConfigureConnection();"/>
                   </td>
               </tr>
            <tr>
               <td colspan="2">
                   <input type    = "button" 
                          id      = "closeConfigureConnectionButton" 
                          class   = "width100" 
                          style   = "height:40px"
                          value   = "Close" 
                          onclick = "document.getElementById('configureConnectionDiv').style.display = 'none';"/>
                   </td>
               </tr>
            </table>
      </div>
</form>

Above, the third function, setCofigureConnection(), does fire; however, the controller action does not:

   [HttpPost]
   public ActionResult SetConfigureConnection(string server, string db, string userID, string password){
          Response.Write("<script>alert('The procedure did activate.');</script>");
          return Json(new {success = true, message = "success"}, JsonRequestBehavior.AllowGet);}

Any ideas?

samedi 23 mai 2015

Make ajax call with controller and action names

On my MVC _layout page I have a button that drops down a panel with an iframe in it.

I want to fill the iframe with the contents of another html page to display help for the current screen with a format like ControllerNameActionNameHelp.html.

How do I get the current Controller Name and Action Name for the Ajax call?

(Or is it the wrong way to do this?)

Which .Net CMS is best in today market [on hold]

I am new to ASP.Net. I want to start working on ASP.Net CMS. Kindly suggest me good CMS among DotNetNuke, Infinity, Kentico etc.

jeudi 21 mai 2015

MVC3 Catch all path segments in URL

I'm trying to embed a legacy Area of our MVC3 application into an iframe within the website's new root layout.

The aim is to save time and avoid Javascript and CSS styling conflicts between new and old sections of the website.

I have so far been able to conditionally redirect traffic from the old Area to a new URL within the OnActionExecuting method in the Area's controllers.

e.g. http://localhost:80/Area/Account/Profile to http://localhost:80/App/Area/Account/Profile

My trouble now is setting up a catch all route that can pass the entire URL to a specific action and controller so I can take the URL and apply it to the iFrame.

I have this in my routing but it does not pass the path to the action and if there is more than one segment in the path it does not hit the route at all:

routes.MapRoute(
    "AppRedirect", // Route name
    "App/{*page}", // URL with parameters
    new { controller = "Home", action = "App", page = UrlParameter.Optional }
);

Is there a way a can get the route working with the full path including all segments?

Or is there a better way to embed one of the projects Areas into an iFrame within the new root layout, while maintaining a readable URL similar to the old configuration? I do not want to modify the structure or routing configuration of the old Area if it can be helped.

why doesn't this set the "User" roles properly?

I have the following code where I am getting the user and their role from a custom database. Then I am trying to set the users role to authenticate certain windows from being displayed if you don’t have the correct role.

I have been following this tutorial to get this far: Custom User Roles

I know that the validation of the user is working as it recognizes the username and password and returns the username, id, etc... from the database.

Using a breakpoint in the code block, I see that the roles variable is correct and the username is correct but the e.User is coming back null and I am not sure why.

This code is in my Global.asax, Can anyone point me in the right direction?

protected void FormsAuthentication_OnAuthenticate(Object sender, FormsAuthenticationEventArgs e)
{
    if (FormsAuthentication.CookiesSupported == true)
    {
        if (Request.Cookies[FormsAuthentication.FormsCookieName] != null)
        {
            try
            {
                //let us take out the username now
                string roles = string.Empty;
                string username = FormsAuthentication.Decrypt(Request.Cookies[FormsAuthentication.FormsCookieName].Value).Name;

                using (RecipeEntities entities = new RecipeEntities())
                {
                   var user = entities.KeyFobUsers.Single(u => u.username == username);

                    roles = user.AccessLevel.Trim();
                }
                //let us extract the roles from our own custom cookie
                //Let us set the Pricipal with our user specific details
                e.User = new System.Security.Principal.GenericPrincipal(new System.Security.Principal.GenericIdentity(username, "Forms"), roles.Split(';'));
            }
            catch (Exception ex)
            {
                //something went wrong
                throw ex;
            }
        }
    }
}

Restrict the global variable should not take assign value which is done outside the class intialization

I have one global variable isSave in my controller.

private bool isSave;

There is Get Method in samecontroller. I want that viewbag given below should be true/false based on condition

ViewBag.EmailConfirmationSent = false;

[HttpGet]
    public ActionResult Index()
    {
if(!isSave)
 ViewBag.EmailConfirmationSent = false;
}

There is post method in same controller

[HttpPost]
    public ActionResult Index(ProfileViewModel profileViewModel)
    {
      bool isSave = SaveDone(); //let say it return true
     ViewBag.EmailConfirmationSent = true;
    return View("Profile", profileViewModel); // redirect to Index method
   }

Now when I make the viewBag true(in post method), it should not change in index method. To restrict that I have used one global variable isSave but whenever it hits the index the global variable "isSave" is always coming false and again my viewBag become false which I don't want. Please let me know how to do this.

mercredi 20 mai 2015

MVC: Want to upload multiple images by Drag and Drop

My problem is how to keep "m.Files" property (this is a property of model) with its old value because m.Files gets the new files and lost the older files selected before.

I want to add drag and drop functionality with preview option. While previewing user can remove any of the image which was mistakenly selected. Then Save all the images on button click. I searched a lot in google but did not get the solution which fulfill my needs.

In my view, i am using below code to select multiple files:

<tr>
<td id="edit_heads" width="170">Choose Screen Image(s)</td>
<td id="edit_fields">
   @Html.TextBoxFor(m=>m.Files, new { type = "file", name = "files[]", id = "choose", accept = ".jpg,.png,.gif", multiple = "multiple", @class = "filedropzone" })
   @Html.ValidationMessageFor(model => model.Files)
</tr>

Please suggest the way to implement this. I will glad to share more information to make the problem more appropriate.

mvc3 partial view & partial postback

I've three partial view and that generates a result in a TextBox :

@Html.Partial("ClassPart", Model)

@Html.Partial("FromDatePart", Model)

@Html.Partial("ToDatePart", Model)

Now there is no problem with the partial view interacting the action in the controller class but when I use drowpdownlistbox or Jquery datepicker it postback the whole form also the data in the view page control is lost, I assign all the values in the action class to in a strongly typed view.

'System.Web.HttpApplication.User' is a 'property' but is used like a 'type'

I am new to MVC3 and I am trying to implement customer user and role Authentication. I am able to validate the user using my custom database but now I want to use my custom roles out of the same table. I followed the instructions from this link below to get this far:

MVC Custom Roles and Validation

The tutorial had me put this block of code in my global.asax file.

protected void FormsAuthentication_OnAuthenticate(Object sender, FormsAuthenticationEventArgs e)
        {
            if (FormsAuthentication.CookiesSupported == true)
            {
                if (Request.Cookies[FormsAuthentication.FormsCookieName] != null)
                {
                    try
                    {
                        //let us take out the username now
                        string roles = string.Empty;
                        string username = FormsAuthentication.Decrypt(Request.Cookies[FormsAuthentication.FormsCookieName].Value).Name;

                        using (RecipeEntities entities = new RecipeEntities())
                        {
                           **-->> User user = entities.KeyFobUsers.Single(u => u.username == username);

                            roles = user.AccessLevel.Trim();
                        }
                        //let us extract the roles from our own custom cookie
                        //Let us set the Pricipal with our user specific details
                        e.User = new System.Security.Principal.GenericPrincipal(new System.Security.Principal.GenericIdentity(username, "Forms"), roles.Split(';'));
                    }
                    catch (Exception)
                    {
                        //something went wrong
                    }
                }
            }
        }

Currently in the script above MVC has 'User' underlined stating that 'System.Web.HttpApplication.User' is a 'property' but is used like a 'type'

I have googled around and tried the links I found on Stack but nothing was geared towards my issue. I am just trying to get the role out of my custom database table into the Roles of MVC so I can use permissions on certain windows.

Does anyone have any suggestions or want to push me in the right direction? Thanks

Is there any way we can rename file in C#?

I know that we can rename using File.Move() but it requires moving file to a new location.

Also it will throw exceptions if already file is present in destination path.

How to Clone Kendo DropdownList using jquery

<div class="target-elements">

@(Html.Kendo().MultiSelect()
      .Name("required")
      .Placeholder("Select attendees...")
      .BindTo(new List<string>() {
          "Steven White",
          "Nancy King",
          "Anne King",
          "Nancy Davolio",
          "Robert Davolio",
          "Michael Leverling",
          "Andrew Callahan",
          "Michael Suyama",
          "Anne King",
          "Laura Peacock",
          "Robert Fuller",
          "Janet White",
          "Nancy Leverling",
          "Robert Buchanan",
          "Andrew Fuller",
          "Anne Davolio",
          "Andrew Suyama",
          "Nige Buchanan",
          "Laura Fuller"
      })
      .Value(new string[] { "Anne King", "Andrew Fuller" })
)

This is my HTML Page in MVC I want to clone this multiselect at run time.

I'm using following javascript :

<script type="text/javascript">

function cloneTargetBox() {
    debugger;
    var targetBoxClone = $(".target-elements:first").clone();
    targetBoxClone.find("input").val("");
    targetBoxClone.insertAfter(".target-elements:last")
}

$(document).ready(function () {
    $(".add").click(cloneTargetBox);
});

It is working if i'm using normal dropdown. but in kendo new added multiselect is not working.

Please suggest.

mardi 19 mai 2015

ASP.NET MVC Routing, TransferRequestHandler dont work in ClassicMode with IIS

I have a web site in my local IIS. The Application Pool for this site it is in Clasic Mode.

I am mapping a path of a file to a route on MVC.

I have the route register like this

   public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        //routes.RouteExistingFiles = true;
        routes.MapRoute(
           name: "XMLPath",
           url: "sitemapindex.xml",
           defaults: new { controller = "Home", action = "Html", page = UrlParameter.Optional }
       );

        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
            );
    }

In my controller I have this method

public FileResult Html()
    {
        var stringBuilder = new StringBuilder();
        stringBuilder.AppendLine("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
        stringBuilder.AppendLine("<sitemapindex xmlns=\"http://ift.tt/xwbjRF\">");
        stringBuilder.AppendLine("<sitemap>");
        stringBuilder.AppendLine("<loc>http://[site]/sitemaps/sitemap_01.xml</loc>");
        stringBuilder.AppendLine("<lastmod>" + DateTime.Now.ToString("MMMM-dd-yyyy HH:mm:ss tt") + "</lastmod>");
        stringBuilder.AppendLine("</sitemap>");
        stringBuilder.AppendLine("<sitemap>");
        stringBuilder.AppendLine("<loc>http://[site]/sitemaps/sitemap_02.xml</loc>");
        stringBuilder.AppendLine("<lastmod>" + DateTime.Now.ToString("MMMM-dd-yyyy HH:mm:ss tt") + "</lastmod>");
        stringBuilder.AppendLine("</sitemap>");
        stringBuilder.AppendLine("</sitemapindex>");

        var ms = new MemoryStream(Encoding.ASCII.GetBytes(stringBuilder.ToString()));



        Response.AppendHeader("Content-Disposition", "inline;filename=sitemapindex.xml");
        return new FileStreamResult(ms, "text/xml");
    }

And in my web.cong I add this

<handlers>
      <add name="HtmlFileHandler" path="*.xml" verb="GET" type="System.Web.Handlers.TransferRequestHandler" preCondition="classicMode,runtimeVersionv4.0" />
    </handlers></system.webServer>
  <runtime>

All this is similar to http://ift.tt/1tzTw9r

The only differences is that using preCondition="classicMode,runtimeVersionv4.0" not preCondition="integratedMode,runtimeVersionv4.0".

If I run the project in Visual Studio 2013 work perfect, but when I run it in the IIS doesn't works. If I change the AppPool of my IIS to integrate mode works. But I need to have the AppPool in Classic Mode.

When I run the Route (url) [site]/sitemapindex.xml in classic mode I get this error:

HTTP Error 500.21 - Internal Server Error Handler "HtmlFileHandler" has a bad module "ManagedPipelineHandler" in its module list

This a Example Project that I am using. How I can used System.Web.Handlers.TransferRequestHandler in classicMode in a IIS Site?

Cutomized DisplayFormatAttribute only setting once

I am setting NullDisplayText in the DisplayFormat from resource through the following code

public class LocalizedDisplayFormatAttribute : DisplayFormatAttribute
{

    private readonly PropertyInfo _propertyInfo;


    public LocalizedDisplayFormatAttribute(string resourceKey, Type resourceType)
        : base()
    {
        this._propertyInfo = resourceType.GetProperty(resourceKey, BindingFlags.Static | BindingFlags.Public);
        if (this._propertyInfo == null)
        {
            return;
        }

        base.NullDisplayText = (string)this._propertyInfo.GetValue(this._propertyInfo.DeclaringType, null);
    }


    public new string NullDisplayText
    {
        get
        {
            return base.NullDisplayText;
        }

        set
        {
            base.NullDisplayText = value;
        }
    }
}

But when I change the culture it does not affecting the NullDisplayText, it's setting only once. I want to change the NullDisplayText according to the culture change.

How to clear @Html.EditorFor

Am new to MVC3. I have a view with following html helpers

 <div class="editor-field">
    @Html.EditorFor(model => model.RoleName)
    @Html.ValidationMessageFor(model => model.RoleName)
 </div>

After First time loading previous value(RoleName) is shown in Editor field until the page is fully loaded.

Right now I am showing a loading image until document is ready.But for learning purpose can I change this behavior so that until model is not binded the editor field is to be cleared?

dimanche 17 mai 2015

When removing model data from a db everything but the primary key is getting deleted, how can i remove all of it?

I am working on a listbox system where the operator can select exercises in a users regime and delete them. Currently when RemoveExercises is called it deletes all of the data associated with the RegimeItem but the RegimeItemID. For the RemoveExercises function, i have started using a Session so that the RequestedExercises listbox is updated with the changes made (the adding and removing of exercises). Any help or suggestions as to why the entire model item is not being deleted is appreciated.

Controller(cs)

    [HttpGet]
    public ActionResult ExerciseIndex(int id, UserExerciseViewModel vmodel)
    {
        User user = db.Users.Find(id);
        UserExerciseViewModel model = new UserExerciseViewModel { AvailableExercises = GetAllExercises(), RequestedExercises = ChosenExercises(user, vmodel) };
        model.UserID = user.UserID;
        Session["UserExerciseViewModel"] = model;
        return View(model);
    }

    [HttpPost]
    public ActionResult ExerciseIndex(UserExerciseViewModel model, string add, string remove, string send, int id, RegimeItem item)//, User rUser) //int userID
    //public ActionResult ExerciseIndex(UserExerciseViewModel model, string add, string remove, string send, int id, RegimeItem item)
    {

        UserExerciseViewModel model2 = (UserExerciseViewModel)(Session["UserExerciseViewModel"]);
        model.RequestedExercises = model2.RequestedExercises;
        model.AvailableExercises = model2.AvailableExercises;
        if (!string.IsNullOrEmpty(add))
            AddExercises(model, id);
        else if (!string.IsNullOrEmpty(remove))
            RemoveExercises(model, id);
        User user = db.Users.Find(id);
        return RedirectToAction("ExerciseIndex", new { id = model2.UserID, vmodel = model2 });
    }

    void RemoveExercises(UserExerciseViewModel model, int id)
    {
        var userExerciseViewModel = (UserExerciseViewModel)(Session["UserExerciseViewModel"]);
        foreach (int selected in model.RequestedSelected)
        {
            if (model.RequestedSelected != null)
            {
                User user = db.Users.Find(id);
                RegimeItem item = db.RegimeItems.Find(selected); // ---deletes the user associated with regimeitem
                item.RegimeExercise = this.GetAllExercises().FirstOrDefault(i => i.ExerciseID == selected); //--this removes the regimeexercise
                user.RegimeItems.Remove(item);
            }
        }
        db.SaveChanges();
    }

    private List<Exercise> GetAllExercises()
    {
        return db.Exercises.ToList();
    }

    private List<RegimeItem> ChosenExercises(User user, UserExerciseViewModel model)
    {
        return db.Users
     .Where(u => u.UserID == user.UserID)
     .SelectMany(u => u.RegimeItems)
     .ToList();
    }

Models(cs)

 public class User
    {
        public int UserID { get; set; }
        public ICollection<RegimeItem> RegimeItems { get; set; }
        public User()
        {
            this.RegimeItems = new List<RegimeItem>();
        } 
    }
    public class RegimeItem
    {
        public int RegimeItemID { get; set; }
        public Exercise RegimeExercise { get; set; }
    }

ViewModel(cs)

public class UserExerciseViewModel
{
    public List<Exercise> AvailableExercises { get; set; }
    public List<RegimeItem> RequestedExercises { get; set; }
    public int? SelectedExercise { get; set; }
    public int[] AvailableSelected { get; set; }
    public int[] RequestedSelected { get; set; }
    public string SavedRequested { get; set; }
    public int UserID { get; set; }
}

ASP.Net MVC and state - How to update the database from Session changes in dual listboxes?

I am working on a dual listbox system where the operator can assign and remove different exercises to a specific users regime. For the RemoveExercises function, i have started using a Session so that the RequestedExercises listbox is updated with the changes made (the adding and removing of exercises).

Currently the AddExercises function adds the exercise from the AvailableExercises listbox to the RequestedExercises listbox (also known as RegimeItems) on the database but it doesn't show up on the RequestedExercises listbox until i go back into the page.

The RemoveExercises function however, removes a selected exercise from the RequestedExercises listbox but doesn't make the changes to the database. So both functions only do half of what i want them to do but in different ways.

This has led me to believe that added exercise is not showing up on the RequestedExercises listbox because of the session state, and the RemoveExercises is not updating its changes to the database. Any help would be greatly appreciated.

UPDATE: after changing return View(model); to return RedirectToAction("ExerciseIndex", new { id = model2.UserID, vmodel = model2 }); in the post request, add exercises works perfectly. How should i make it so that RemoveExercises works on the domain object User?

Controller.cs

    [HttpGet]
    public ActionResult ExerciseIndex(int id, UserExerciseViewModel vmodel)
    {
        User user = db.Users.Find(id);
        UserExerciseViewModel model = new UserExerciseViewModel { AvailableExercises = GetAllExercises(), RequestedExercises = ChosenExercises(user, vmodel) };
        model.UserID = user.UserID;
        Session["UserExerciseViewModel"] = model;
        return View(model);
    }

    [HttpPost]
    public ActionResult ExerciseIndex(UserExerciseViewModel model, string add, string remove, string send, int id, RegimeItem item)
    {
        UserExerciseViewModel model2 = (UserExerciseViewModel)(Session["UserExerciseViewModel"]);
        model.RequestedExercises = model2.RequestedExercises;
        model.AvailableExercises = model2.AvailableExercises;
        if (!string.IsNullOrEmpty(add))
            AddExercises(model, id);
        else if (!string.IsNullOrEmpty(remove))
            RemoveExercises(model, id);
        User user = db.Users.Find(model2.UserID);
        model2.RequestedExercises = ChosenExercises(user, model);
        user.RegimeItems = model.RequestedExercises;
        RestoreSavedState(model, user);
        return RedirectToAction("ExerciseIndex", new { id = model2.UserID, vmodel = model2 });
    )

    void RemoveExercises(UserExerciseViewModel model, int id)
    {
        var userExerciseViewModel = (UserExerciseViewModel)(Session["UserExerciseViewModel"]);
        foreach (int selected in model.RequestedSelected)
        {
            RegimeItem item = model.RequestedExercises.FirstOrDefault(i => i.RegimeItemID == selected);
            if (item != null)
            {
                model.RequestedExercises.Remove(item);
            }
        }
        db.SaveChanges();
    }

    void AddExercises(UserExerciseViewModel model, int id)
    {
        var userExerciseViewModel = (UserExerciseViewModel)(Session["UserExerciseViewModel"]);
        foreach (int selected in model.AvailableSelected)
        {
            if (model.AvailableSelected != null)
            {
                User user = db.Users.Find(id);
                user.RegimeItems.Add(new RegimeItem()
                {
                    RegimeExercise = (this.GetAllExercises().FirstOrDefault(i => i.ExerciseID == selected))
                });
            }
        }
        db.SaveChanges();
    }

    void RestoreSavedState(UserExerciseViewModel model, User user)
    {
        user.RegimeItems = this.ChosenExercises(user, model);
        if (!string.IsNullOrEmpty(model.SavedRequested))
        {
            string[] exIds = model.SavedRequested.Split(',');
            var regimeItems = ChosenExercises(user, model).Where(p => exIds.Contains(p.RegimeItemID.ToString()));
            model.RequestedExercises.AddRange(regimeItems);
        }
        db.SaveChanges();
    }

    private List<Exercise> GetAllExercises() //Gets all the data for AvailableExercises
    {
        return db.Exercises.ToList();
    }

    private List<RegimeItem> ChosenExercises(User user, UserExerciseViewModel model) //Gets all the data for RequestedExercies
    {
     return db.Users
     .Where(u => u.UserID == user.UserID)
     .SelectMany(u => u.RegimeItems)
     .ToList();
    }

Models(cs)

 public class User
    {
        public int UserID { get; set; }
        public ICollection<RegimeItem> RegimeItems { get; set; }
        public User()
        {
            this.RegimeItems = new List<RegimeItem>();
        } 
    }
    public class RegimeItem
    {
        public int RegimeItemID { get; set; }
        public Exercise RegimeExercise { get; set; }
    }

ViewModel(cs)

public class UserExerciseViewModel
{
    public List<Exercise> AvailableExercises { get; set; }
    public List<RegimeItem> RequestedExercises { get; set; }
    public int? SelectedExercise { get; set; }
    public int[] AvailableSelected { get; set; }
    public int[] RequestedSelected { get; set; }
    public string SavedRequested { get; set; }
    public int UserID { get; set; }
}

View(Segment Only(cshtml))

<td valign="top">
   @Html.ListBoxFor(model => model.AvailableSelected, new MultiSelectList(Model.AvailableExercises, "ExerciseID", "Name", Model.AvailableSelected))
</td>
<td valign="top">
  <input type="submit" name="add"
  id="add" value=">>" /><br />
  <input type="submit" name="remove"
  id="remove" value="<<" />
</td>
<td valign="top">
    @Html.ListBoxFor(model => model.RequestedSelected, new MultiSelectList(Model.RequestedExercises, "RegimeItemID", "RegimeExercise.Name", Model.RequestedSelected))
</td>

How to implement client side validation in MVC with chosen.js

I am using chosen.js for multiple selection. Implemented this with asp.net mvc3,now client side validation is not working this multi select control.

The way i implemente is ,using Html.Dropdownlist helper and once the dom loaded from javascript $("#dropdown1").chosen().

It is replacing the Select with div's.

Please help me on this.

Thanks, Yuvraj

jeudi 14 mai 2015

How to increase performance of foreach loop

I'm using a foreach loop to calculate answers against question.

It calculates all the answers against a question but when it loads the next question it takes one minute every time. How can I reduce this time?

List<Questionnaire> myQuestionnaires = report.Project
                                             .Questionnaires
                                             .Where(q => q.Active)
                                             .ToList<Questionnaire>();          

foreach (Questionnaire q in myQuestionnaires)
{
    foreach (ItemAnswer a in q.Answers)
    {
        //possible answers 
    }
}                

How Route Map direct to .html without controller?

I have a problem, I can't direct display test.html without using controller.

I used this http://ift.tt/1PkWr3A

and this is the error display enter image description here

here is my VS studio

enter image description here

Note: I will not use controller to this display html like

 public virtual ActionResult test(Index index)

I want is to direct view will pass through controller.

any Idea please? thank you.

mercredi 13 mai 2015

'the 'Iscomposable' attribute is not allowed' Downgrade from .NET4.5 to 4.0

I had to downgrade asp.net mv4 web application from .Net Framework 4.5 to 4.0. I have fixed all the assembly references issues, but unable to fix the following errors that are with Model.edmx:

  1. the 'Iscomposable' attribute is not allowed
  2. 'The element 'Function' in namespace 'http://ift.tt/1dAEaeL' has invalid child element 'ReturnType' in namespace 'http://ift.tt/1dAEaeL'. List of possible elements expected: 'Parameter' in namespace 'http://ift.tt/1dAEaeL' as well as any element in namespace '##other'.'

XML code for these issues are:

<Function Name="Get_temp" Aggregate="false" BuiltIn="false" NiladicFunction="false" IsComposable="true" ParameterTypeSemantics="AllowImplicitConversion" Schema="dbo">
  <Parameter Name="deviceid" Type="bigint" Mode="In" />
  <Parameter Name="Datestart" Type="datetime" Mode="In" />
  <Parameter Name="dateend" Type="datetime" Mode="In" />
  <ReturnType>
    <CollectionType>
      <RowType>
        <Property Name="data" Type="int" Nullable="false" />
      </RowType>
    </CollectionType>
  </ReturnType>
</Function>

As i am new to asp.net mvc 4. Kindly guide me what else is left or what needs to be done to fix this issue.

Thanks in Advance

MVC Action link with dynamic parameters

I am using MVC and my requirement is that i need to build a action link with dynamic action route value.

for example.

In my model i have the list<string> so action link should be.

../ActionMethodName/ControllerName? Item[0]=model.item[0]&Item[1]=model.Item[1]...so on.

Any Suggestion is welcome.

mardi 12 mai 2015

Is it possible to use an anonymous object in Controller-Method?

is it possible to use an anonymous object in a Controller Method?

e.g.

[HttpPost]
public ActionResult Test(/*Anonymous object here*/){
/*Do something here */
}

function GetSomething(settings, inputData) {
$.ajax({
    url: settings.url,
    type: 'POST',
    dataType: 'html',
    data: inputData,
    success: function (data) {
        $('#' + settings.target + '').html(data);
    }
});

}

Now I'd like to build a for example User-Object inside the Ajax-function

inputdata.Firstname: 'Max',
inputdata.Lastname: 'Mustermann',
inputdata.Age: 25

After that I'd like to use the "User-object" inside my Controller Method

public Actionresult Test(/*object*/ user){
    if(String.IsNullOrEmpty(user.Firstname.ToString()){
    /*Do something*/
    }
} 

Unable to install MVC 3

I am attempting to install asp.net MVC 3 to use with Visual Web Developer 2010 Express. I try to install from AspNetMVC3ToolsUpdateSetup.exe. The install log shows this:

MSI (s) (08:E4) [00:22:35:745]: Product: Microsoft ASP.NET MVC 3 -- A later version of Microsoft ASP.NET MVC 3 is already installed. Setup will now exit.

A later version of Microsoft ASP.NET MVC 3 is already installed. Setup will now exit.

I have MVC 2 installed (it came with VWD 2010). I do not see MVC3 or MVC4 in installed programs list. I don't have NuGet installed. How could I manage to install it?

How to assign a Selected value to a selected item in a Listbox so that it can be deleted?

I am currently working on a listbox that needs to have a function to remove/delete items from the listbox and ultimately the database. When an item(RegimeItem) is selected in the listbox, then the remove button is pressed the item is deleted from the database, that is what i want to happen.

The RequestedSelected part of the foreach statement in the RemoveExercises method of the controller is currently null, what i want to know is how do i make it so that it isn't? From what i understand is that when the item is selected in the listbox that is not recognized as RequestedSelected

Controller

    [HttpGet]
    public ActionResult ExerciseIndex(int? id, UserExerciseViewModel vmodel)
        {
            User user = db.Users.Find(id);
            UserExerciseViewModel model = new UserExerciseViewModel { AvailableExercises = GetAllExercises(), RequestedExercises = ChosenExercises(user, vmodel) };
            user.RegimeItems = model.RequestedExercises;
            return View(model);
        }
        [HttpPost]
        public ActionResult ExerciseIndex(UserExerciseViewModel model, string add, string remove, string send, int id, RegimeItem regimeItem)
        {
            User user = db.Users.Find(id);
            user.RegimeItems = model.RequestedExercises;
            RestoreSavedState(model);
            if (!string.IsNullOrEmpty(add))
                AddExercises(model, id);
            else if (!string.IsNullOrEmpty(remove))
                RemoveExercises(model, id);              
            SaveState(model);
            return View(model);
        }

        void SaveState(UserExerciseViewModel model)
        {
            model.SavedRequested = string.Join(",", model.RequestedExercises.Select(p => p.RegimeItemID.ToString()).ToArray());
            model.AvailableExercises = GetAllExercises().ToList();
        }

        void RemoveExercises(UserExerciseViewModel model, int id)
        {
            foreach (int selected in model.RequestedSelected)
        {
            RegimeItem item = model.RequestedExercises.FirstOrDefault(i => i.RegimeItemID == selected);
            if (item != null)
            {
                User user = db.Users.Find(id);
                user.RegimeItems.Remove(item);
            }
            RedirectToAction("ExerciseIndex");
        }

        void RestoreSavedState(UserExerciseViewModel model)
        {
            model.RequestedExercises = new List<RegimeItem>();

            //get the previously stored items
            if (!string.IsNullOrEmpty(model.SavedRequested))
            {
                string[] exIds = model.SavedRequested.Split(',');
                var exercises = GetAllExercises().Where(p => exIds.Contains(p.ExerciseID.ToString()));
                model.AvailableExercises.AddRange(exercises);
            }
        }

private List<Exercise> GetAllExercises()
        {
            return db.Exercises.ToList();
        }

        private List<RegimeItem> ChosenExercises(User user, UserExerciseViewModel model)
        {
            return db.Users
            .Where(u => u.UserID == user.UserID)
            .SelectMany(u => u.RegimeItems)
            .ToList();
        }

Models

 public class User
    {
        public int UserID { get; set; }
        public ICollection<RegimeItem> RegimeItems { get; set; }
        public User()
        {
            this.RegimeItems = new List<RegimeItem>();
        } 
    }
    public class RegimeItem
    {
        public int RegimeItemID { get; set; }
        public Exercise RegimeExercise { get; set; }
    }

ViewModel

public class UserExerciseViewModel
{
    public List<Exercise> AvailableExercises { get; set; }
    public List<RegimeItem> RequestedExercises { get; set; }
    public int? SelectedExercise { get; set; }
    public int[] AvailableSelected { get; set; }
    public int[] RequestedSelected { get; set; }
    public string SavedRequested { get; set; }
}

View(Segment only)

      <input type="submit" name="remove"
             id="remove" value="<<" />
  </td>
  <td valign="top">
      @Html.ListBoxFor(model => model.RequestedExercises, new MultiSelectList(Model.RequestedExercises, "RegimeItemID", "RegimeExercise.Name", Model.RequestedSelected))
  </td>

lundi 11 mai 2015

how to return a value from JsonResult to the bootstrap fileinput

Good evening, I'm using the api bootstrap fileinput and I wonder if you can return a value with ContetResult and uses it in my View.

my Test Controller method ContentResult (just a test):

public ContentResult upload()
{

    string name = "";
    for (int i = 0; i < Request.Files.Count; i++) 
    { 
        HttpPostedFileBase file = Request.Files[i];
        name = file.FileName;
    }

     return Content("{\"name\":\"" + name + "\"}", "application/json");

}

and my View:

<input id="input-701" name="kartik-input-701[]" type="file" multiple=true class="file-loading" />
<input type="text" class="file_name" />

<script type="text/javascript">

    $("#input-upload").fileinput({ 'showUpload': true, 'previewFileType': 'any' });

    $("#input-701").fileinput({

        uploadUrl: '@Url.Action("upload", "Home")', // server upload action
        uploadAsync: false,
        maxFileCount: 50,


        sucess: function (e, data) {

            $('.file_name').html(data.result.name);

        }
    });


</script>

so I want to do something like this illustrative atributte: sucess

Thanks for the help!

I'm using ninject 3.0 and asp.net mvc 3. I get the error rror activating IProductRepository

I am new to MVC so im fallowing a book example. But when I run the program it gives me the error: Error activating IProductRepository No matching bindings are available, and the type is not self-bindable. Activation path...

I have read a bunch of articles and other error like this one but none of them helped. Why is this happening if everything is the same as in the book example? Please some help would be really appreciated.

public class NinjectControllerFactory : DefaultControllerFactory
{
    private IKernel ninjectKernel;

    public NinjectControllerFactory()
    {
        ninjectKernel = new StandardKernel();
    }

    protected override IController GetControllerInstance(RequestContext requestContext,
       Type controllerType)
    {
        return controllerType == null
            ? null
            : (IController)ninjectKernel.Get(controllerType);
    }

    private void AddBindings()
    {
        ninjectKernel.Bind<IProductRepository>().To<EFProductRepository>(); 
    }
}

Global.asax.cs

 protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();

        RegisterGlobalFilters(GlobalFilters.Filters);
        RegisterRoutes(RouteTable.Routes);
        ControllerBuilder.Current.SetControllerFactory(new NinjectControllerFactory());
    }

IProductRepository.cs

public interface IProductRepository
{
    IQueryable<Product> Products { get; }
}

EFProductRepository.cs

public class EFProductRepository : IProductRepository
{
   private EFDbContext context = new EFDbContext();
   public IQueryable<Product> Products
    {
        get { return context.Products; }           
    }
}

public class EFDbContext : DbContext
{
    public DbSet<Product> Products { get; set; }    
}

ProductController.cs

public class ProductController : Controller
{
    private IProductRepository repository;

    public ProductController(IProductRepository repoParam)
    {
        repository = repoParam;
    }

    public ViewResult List()
    {
        return View(repository.Products);
    }
}

Html.Telerik().EditorFor not working in Firefox

I have a telirik html text box in a editor template in my view (MVC3). It is loading fine in IE and chrome but when i open in Firefox html text box becomes read only. How do I resolve my issue.

Find the piece of code here.

  @(Html.Telerik().EditorFor(m => m.HtmlText).Encode(false).
                            .Tools(tools => tools.Clear()
                            .Bold().Italic().Underline()                                     ))

dimanche 10 mai 2015

static variables in web site and web application C#

I have same codes which work differently on 2 different IIS servers which one is set as web site and another is set as web application.

I have 2 classes.

public class Config1{
    public static string RelativePath {get; set;}
}

public class Config2{
    public static readonly string FavIconPath = Config1.RelativePath;
}

And I assign value from web.config in Global.asax.cs

protected void Application_Start(){
    Config1.RelativePath = getWebConfigValue("Path");
}

I use it in view files like below.

RelativePath : @Config1.RelativePath<p/>
FavIconPath : @Config2.FavIconPath

The results are

On web site server
RelativePath : somevalue
FavIconPath : 

On web application server
RelativePath : somevalue
FavIconPath : somevalue

Is there any differences of instantiate timing between web site and web application? Any help would be appreciated!

Update MVC from 4.0 to 5.2 - Could not install package

Im trying to update my project from MVC 4.0 to 5.2. But As soon I do that I get an error message:

Install-Package : Could not install package 'Microsoft.AspNet.Razor 3.2.3'. You are trying to install this packag e into a project that targets '.NETFramework,Version=v4.0', but the package does not contain any assembly referen ces or content files that are compatible with that framework. For more information, contact the package author. At line:1 char:1 + Install-Package Microsoft.AspNet.Mvc -Version 5.2.3 + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : NotSpecified: (:) [Install-Package], InvalidOperationException + FullyQualifiedErrorId : NuGetCmdletUnhandledException,NuGet.PowerShell.Commands.InstallPackageCommand

How can I Sovle this issue? And What does this mean?

vendredi 8 mai 2015

How to download files with filename containing special characters using .Net WebClient

I am getting an error “400 – Bad Request” while using .Net WebClient to download files with filename containing certain characters:

For example if the file is named: 5L1XQE6FTest #.mp4 this generates an error.

If I remove the # sign the file is downloaded fine:

Here is my code:

  public ActionResult DownloadVideoFile(string filepath)
        {
            try
            {

               filepath = "http://localhost:1832/VideoUploads/" + filepath;
                var type = new System.Net.Http.Headers.MediaTypeHeaderValue("application/octet-stream");
                var path = Path.GetFileName(filepath);

                using (var client = new WebClient())
                {

                    var buffer = client.DownloadData(filepath);
                    return File(buffer, type.ToString(), path);
                }

            }
            catch (Exception e)
            {
                var test = e.Message;
            }
            return null;

        }

When I url encode the file name I still get the same error.

I have no control over the filename that I am trying to download as files are user submitted.

How can I resolve the Bad Request error while downloading files with special or reserved characters?

How to delete an item from this listbox?

I have a listbox where i need to be able to remove individual RegimeItems. These RegimItems belong to a specific user, but as they are right now the listbox shows them for specific user, so i don't know if i need to state that in the code. Currently it is showing no error however it does not return the listbox with the remaining RegimeItems, nor does it actually update the database with the changes.

Update: i am getting a null reference exception atmodel.RequestedSelected on the line foreach (int selected in model.RequestedSelected) in RemoveExercises.

Controller

    [HttpGet]
    public ActionResult ExerciseIndex(int? id, UserExerciseViewModel vmodel)
        {
            User user = db.Users.Find(id);
            UserExerciseViewModel model = new UserExerciseViewModel { AvailableExercises = GetAllExercises(), RequestedExercises = ChosenExercises(user, vmodel) };
            user.RegimeItems = model.RequestedExercises;
            return View(model);
        }
        [HttpPost]
        public ActionResult ExerciseIndex(UserExerciseViewModel model, string add, string remove, string send, int id, RegimeItem regimeItem)
        {
            User user = db.Users.Find(id);
            user.RegimeItems = model.RequestedExercises;
            RestoreSavedState(model);
            if (!string.IsNullOrEmpty(add))
                AddExercises(model, id);
            else if (!string.IsNullOrEmpty(remove))
                RemoveExercises(model, id);              
            SaveState(model);
            return View(model);
        }

        void SaveState(UserExerciseViewModel model)
        {
            model.SavedRequested = string.Join(",", model.RequestedExercises.Select(p => p.RegimeItemID.ToString()).ToArray());
            model.AvailableExercises = GetAllExercises().ToList();
        }

        void RemoveExercises(UserExerciseViewModel model, int id)
        {
            foreach (int selected in model.RequestedSelected)
        {
            RegimeItem item = model.RequestedExercises.FirstOrDefault(i => i.RegimeItemID == selected);
            if (item != null)
            {
                User user = db.Users.Find(id);
                user.RegimeItems.Remove(item);
            }
            RedirectToAction("ExerciseIndex");
        }

        void RestoreSavedState(UserExerciseViewModel model)
        {
            model.RequestedExercises = new List<RegimeItem>();

            //get the previously stored items
            if (!string.IsNullOrEmpty(model.SavedRequested))
            {
                string[] exIds = model.SavedRequested.Split(',');
                var exercises = GetAllExercises().Where(p => exIds.Contains(p.ExerciseID.ToString()));
                model.AvailableExercises.AddRange(exercises);
            }
        }

private List<Exercise> GetAllExercises()
        {
            return db.Exercises.ToList();
        }

        private List<RegimeItem> ChosenExercises(User user, UserExerciseViewModel model)
        {
            return db.Users
            .Where(u => u.UserID == user.UserID)
            .SelectMany(u => u.RegimeItems)
            .ToList();
        }

Models

 public class User
    {
        public int UserID { get; set; }
        public ICollection<RegimeItem> RegimeItems { get; set; }
        public User()
        {
            this.RegimeItems = new List<RegimeItem>();
        } 
    }
    public class RegimeItem
    {
        public int RegimeItemID { get; set; }
        public Exercise RegimeExercise { get; set; }
    }

ViewModel

public class UserExerciseViewModel
{
    public List<Exercise> AvailableExercises { get; set; }
    public List<RegimeItem> RequestedExercises { get; set; }
    public int? SelectedExercise { get; set; }
    public int[] AvailableSelected { get; set; }
    public int[] RequestedSelected { get; set; }
    public string SavedRequested { get; set; }
}

View(Segment only)

      <input type="submit" name="remove"
             id="remove" value="<<" />
  </td>
  <td valign="top">
      @Html.ListBoxFor(model => model.RequestedExercises, new MultiSelectList(Model.RequestedExercises, "RegimeItemID", "RegimeExercise.Name", Model.RequestedSelected))
  </td>

(ASP.NET MVC) Files Served in the Browser Have No Extension

I have the following code that serves the file to the user in the browser. The file has no extension, and the users have to add the extension manually in order to open it.

public ActionResult OpenDoc(int id = 0)
{
    Document doc = dbContext.Documents.Single(d => d.DocID == id);

    byte[] data = (byte[])doc.Data;
    string mimeType = doc.MimeType;
    return File(data, mimeType, doc.DocName);
}

When I debug, I see that the mimeType is "application/pdf" which is correct. However, the file is being served without the pdf extension. Why is that and how can I correct it? Thanks in advance...

jeudi 7 mai 2015

calling a MVC 3 Apicontroller from another website

I have a mvc 3 api controller in my project

namespace Carabistouille.Controllers
{
    public class CarabistouilleController : ApiController
    {
        /// <summary>
        /// Method to retrieve all of the carabistouille in the catalog.
        /// Example: GET api/carabistouille
        /// </summary>
        [HttpGet]
        public HttpResponseMessage Get()
        {
            IEnumerable<Carabistouille.DB.Carabistouille> list = Carabistouille.DB.CarabistouilleDAL.GetAllCarabistouille();
            if (list != null)
            {
                return   Request.CreateResponse<IEnumerable<Carabistouille.DB.Carabistouille>>(HttpStatusCode.OK, list);
            }
            else
            {
                return Request.CreateResponse(HttpStatusCode.NotFound);
            }
        }
    }
}

and I want other website to be able to query that api to get the data so i do something like this :

        $("#query_results").empty();
        $("#query_results").append('<table id="ResultsTable" class="BooksTable"><tr><th>Description</th><th>Auteur</th><th>Date</th></tr>');
        $.ajax({
            type: "get",
            contentType: "application/json; charset=utf-8",     

            url: "http://ift.tt/1PthdbV",
            success: function(msg) {
                    var c = eval(msg.d);
                    for (var i in c) {
                            $("#ResultsTable tr:last").after("<tr><td>" + c.Description + "</td><td>" + c.Auteur + "</td><td>" + c.Date + "</td></tr>");
                        }
                }
        });

Well all i get is :

Failed to load resource: net::ERR_NAME_NOT_RESOLVED

here is my project architecture

enter image description here

what am i missing ?

Calling Webapi 2 service from MVC 5 controller

I want to call a webapi 2 service from MVC 5 controller, can anybody please help me out and give me some easy to understand examples. Thanks.

accessing virtual actionresult in mvc

I want to know how can I access virtual actionresult, since I haven't seen so far this type of actionresults. I've read little bit and I can see that is related to t4mvc but I'm not sure how can I access it.

This is what I have, ScheduleController, which has this actionresult for example:

[Authorize]
    public virtual ActionResult AdminSport(int sportId)
    {
      Sport sport = _rep.GetSport(sportId);
      if(sport == null)
      {
        return this.ViewNotFound();
      }
      if(!User.IsScheduleAdmin(sport))
      {
        return this.ViewNotAuthorized();
      }
      var ret = _rep.ListScheduleEntriesForAD(sport);
      return View(ret);
    }

Then, the only other instance of that controller I found was in T4MVC, and this is whats in that file:

[NonAction]
        partial void AdminSportOverride(T4MVC_System_Web_Mvc_ActionResult callInfo, int sportId);

        [NonAction]
        public override System.Web.Mvc.ActionResult AdminSport(int sportId)
        {
            var callInfo = new T4MVC_System_Web_Mvc_ActionResult(Area, Name, ActionNames.AdminSport);
            ModelUnbinderHelpers.AddRouteValues(callInfo.RouteValueDictionary, "sportId", sportId);
            AdminSportOverride(callInfo, sportId);
            return callInfo;
        }

My question is how can I access that specific action, for example if I type in the browser: /Schedule/AdminSport I'm getting an error.

Any idea what/how do I need to fix this?

Thanks in advance, Laziale

web api stopped working after adding odata

WebApi's were working fine, then I added a few odata controllers, now my webapi's return not found. I assume its in the routing somewhere but I don't see it. returns 404 not found. how do I fix my webapi's to return data gain.

Global Config

    protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();           
        GlobalConfiguration.Configure(WebApiConfig.Register);
        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
        RouteConfig.RegisterRoutes(RouteTable.Routes);
        BundleConfig.RegisterBundles(BundleTable.Bundles);
    }

Web API Config

 public static void Register(HttpConfiguration config)
        {
            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}/{action}",
                defaults: new { id = RouteParameter.Optional }
            );

            ODataConventionModelBuilder builder = new ODataConventionModelBuilder();
            builder.EntitySet<pp_tsr_accounts_tab_Result>("pp_tsr_accounts_tab_Result");
            config.Routes.MapODataServiceRoute("odata", "odata", builder.GetEdmModel());

            config.EnableSystemDiagnosticsTracing();
        }

Call

http://localhost:xxx/api/pp_tsr_offer_calc_Result/Getpp_tsr_offer_calc_Result?id=0801314923

Can Grunt run a .cshtml (asp.net mvc) file?

I have a project that I am working on that has:

  • backend done with ASP.NET MVC ( the web API)
  • frontend done with Angular-JS , Grunt and Node JS.

The question posed here for the team was:

  • Have a part of the page ( a menu, navbar for example) being controlled my ASP.MVC and the rest (content) to be generated/controlled by angular.

Would NodeJS be able to do this (frankenstein-ish) task?

mercredi 6 mai 2015

Complexe Date Query SQL

I would like to add a Date filter to this code:

var db = Database.Open("Tool") ;
var selectCommand = "SELECT Nom, COUNT(Nom) FROM DTool2 AS NumberOfOrders Group by Nom ";

var selectedData = db.Query(selectCommand);
var grid = new WebGrid(source: selectedData, defaultSort: "Column1", rowsPerPage:200); 
grid.SortDirection = SortDirection.Descending;

The date would be picked from inputs (type=date)...

Can anyone help me please

Selecting Item from Database loaded DropDownList and displaying data

I have a drop down list loaded from the database and I want to display data based on specific items in the drop down list. In the where clause it compares the drop down list with the selected item and displays all the information for that event.

Also I have an exception on the @Html.DropDownList("RaceEvent);

An exception of type 'System.InvalidOperationException' occurred in System.Web.Mvc.dll but was not handled in user code

Additional information: The ViewData item that has the key 'RaceEvent' is of type 'System.String' but must be of type 'IEnumerable'.

The controller looks like this

private raceEntities db = new raceEntities();
    // GET: Registrants
    public ActionResult Index()
    {

        var regist = new SelectList(db.raceevents, "RaceEventID", "Name").ToString();

        ViewBag.RaceEvent = regist;

        /* iterate through raceevent table grab Name column convert to string
        var qry = (from rac in db.raceevents
                  select new { rac.Name }).ToString();
        */

        var registrants = (from per in db.people
                           join personorgrole in db.personorganizationroles on per.PersonID equals personorgrole.PersonID
                           join personeve in db.personevents on personorgrole.PersonOrganizationRoleID equals personeve.PersonOrganizationRoleID
                           join eventcla in db.eventclasses on personeve.RaceEventID equals eventcla.RaceEventID
                           join personeventcla in db.personeventclasses on eventcla.EventClassID equals personeventcla.EventClassID
                           join raceeve in db.raceevents on eventcla.RaceEventID equals raceeve.RaceEventID
                           join organizationrolety in db.organizationroletypes on personorgrole.OrganizationRoleTypeID equals organizationrolety.OrganizationRoleTypeID
                           //where raceeve.Name == "Ruapehu Gravity Festival"
                           where raceeve.Name == regist  //raceeve.Name matches the selectlist above 
                          // where raceeve.Name == qry //compare event name with the query above
                           select new Registrants { LastName = per.LastName, FirstName = per.FirstName, RoleType = organizationrolety.Name }).Distinct().OrderBy( per => per.LastName);

        return View(registrants);
    }

The view looks like this

@model IEnumerable<IDFWebApp.Models.Custom.Registrants>
@{
    ViewBag.Title = "Event Registrants";
}

<h2>Event Registrants</h2>
@using (Html.BeginForm())
{
@Html.DropDownList("RaceEvent") //references from ViewBag.RaceEvent in the controller

<table style="width:100%">
    <tr>
        <th>First Name</th>
        <th>Last Name</th>
        <th>Role Type</th>
    </tr>
    @foreach (var person in Model)
    {
        <tr>
            <td>@person.LastName</td>
            <td>@person.FirstName</td>
            <td>@person.RoleType</td>
        </tr>
    }
</table>

}

submit addtional data with form in mvc jquery post

I need to save data from HTML table and other form fields when i post form. Here i need to post form and additional array data to action.This is code i have tried.

sample View

     <div class="form-group">
                                <label for="Support" class="col-sm-2 control-label">Support Desired</label>
                                <div class="col-sm-10">
                                    @Html.TextAreaFor(model => model.SupportDesired, new { @class = "form-control", @placeholder = "Support Desired", @tabindex = "4" })
                                </div>

                            </div>

<div class="form-group">

                        <div class="col-sm-10">
                            <table class="table table-condensed" id="tblselectedcontact">
                                <thead>
                                    <tr>
                                        <th style="width: 30px"></th>
                                        <th>Name</th>
                                        <th>Designation</th>
                                        <th>Department</th>
                                        <th>Phone</th>
                                    </tr>
                                </thead>
                                <tbody>
                                <tr>
                                    <td><a href="#" class="glyphicon glyphicon-remove" onclick="CloseUserRow(this)"></a></td>
                                    <td><input data-val="true" data-val-number="The field ContactId must be a number." data-val-required="The ContactId field is required." id="customer_ContactId" name="customer.ContactId" value="1" type="hidden">ABC</td>
                                    <td>ABC</td>
                                    <td>ABC</td>
                                    <td>ABC</td>

                                </tr></tbody>
                            </table>
                        </div>

                    </div>
............../*all fields goes like this*/
..........

Script Code

function postform() {
    var ActivityContacts= [];

        $('#tblselectedcontact input:hidden').each(function () {

            ActivityContacts.push({
                "ContactId": $(this).val()
            });
        });
        var data = $('#frmCreate').serializeArray();
        data.push(ActivityContacts);
        console.log(ActivityContacts);
        $.post('@Url.Action("Create")', data);
}

Action Method

[HttpPost]
        public ActionResult Create(Model.Activity model)
        {            
           //Create code goes here
        }

Here in action method i get all form fields in model but there is no additional data found.

Image displaying error from database

After the recent changes in my application still i get this issue while displaying the image using the relative path in the database. Error: 404 NOT FOUND http://localhost:1256/Empdet/%22/Photos/jobs.jpg%22

Screenshot

Controller.js:

 $scope.UploadFile = function () {
    console.log('UploadFile');
    console.log($scope.Empdet.PhotoFile);
    var file = $scope.Empdet.PhotoFile;
    console.log('file is ' + JSON.stringify(file));
    var uploadUrl = "../Photos";
    console.log('before file upload');
    EmployeeFactory.UploadFile(file, uploadUrl).success(function (response)  {
        $scope.Empdet.PhotoText = response;
        console.log('$scope.Empdet.PhotoText');
        console.log(response);
    }).error(function () {
        console.log('error');
    });
    console.log('after file upload');
};

service.js:

service.UploadFile = function (file, uploadUrl) {
    var fd = new FormData();
    fd.append('file', file);
    return $http.post('/Empdet/UploadFile', fd, {
        transformRequest: angular.identity,
        headers: { 'Content-Type': undefined }
    });
}

EmpdetController.cs:

[HttpPost]
    public ActionResult UploadFile()
    {
        var file = Request.Files[0];
        var path = Path.Combine(Server.MapPath("~/Photos/"), file.FileName);
        file.SaveAs(path);

        // prepare a relative path to be stored in the database and used to display later on.
        var filename = Url.Content("~/Photos/" + file.FileName);
        // save to db
        return Json(filename.ToString(), JsonRequestBehavior.AllowGet);

    }

I don't want to include td in dr when drag and sortable

I have the following table that pull out from database within loop. I would like to drag and drop the following rows. My problem is when I drag the row, I don't want to include "Save" column.

enter image description here

Thanks

mardi 5 mai 2015

I want to redirect user to new page with his login details appended in the url [on hold]

My question is- Suppose a user uses facebook to login then i want to redirect user to new page with his login details appended in the url.How to achieve this in asp.net mvc.Will query string be able to fetch details from social login page as we does with normal forms.

How to Update View if any change occurs in Data Using controller function in Angular js?

I am trying to update view in mvc3 by sending a get request to controller function. Controller function works fine and on success sends back json data. When page is being refreshed view is updated. I am unable to understand how to update a view asynchronously if any change occurs in database using controller function. So far I have tried this:

var chatApp = angular.module('chatApp', []);
chatApp.controller('GetChatCtrl', function ($scope, $http)
{
    $http.get('Dashboard/GetChatMessages').success(function (data, status, headers, config) 
    {
        $scope.getChat = data; 
    }).error(function (data, status, headers, config) 
    {
        alert("service unavilable");
    });
});

In controller function I am getting data and sending it back json

public JsonResult GetChatMessages() 
{
    try
    { 
        return Json(chatMessages.ToList(), JsonRequestBehavior.AllowGet);
    }
    catch (Exception ex)
    {
    }
}

In view using ng-repeat to get chat messages like this

<div ng-repeat="chat in getChat" class="row">
    <p>{{chat.Username}}</p> <p>{{chat.DateTime}}</p> <p>{{chat.ChatMsg}}</p>
</div>

How it can be done if any change occurs in data base it updates a view. Any suggestions ?

lundi 4 mai 2015

Undo changes done by last database save

When I press a button, jQuery uses ajax to delete an item, but it is possible for me to make another function that can "undo" the deletion that just took place?

My delete controller

    [HttpPost]
    public void DeleteProject(int Id)
    {
        var Item = from a in db.Project
                   where a.ProjectId.Equals(Id)
                   select a;

        Project SelectedProject = Item.FirstOrDefault();
        ICollection<ProjectProfile> Profiles = SelectedProject.ProjectProfile;
        ICollection<Member> Members = SelectedProject.Member;

        db.Member.RemoveRange(Members);
        db.ProjectProfile.RemoveRange(Profiles);

        db.Project.Remove(SelectedProject);
        db.SaveChanges();

        RedirectToAction("Index", "Projects");
    }

Unity.Mvc3 vs Unity.Mvc

Using the Unity.Mvc3 with a Mvc 3 application, i could register my IDummyService as follows:

container.RegisterType<IDummyService, DummyService>(new HierarchicalLifetimeManager());

On each web request, a new instance of my IDummyService is created (as explained in this article), but since I upgraded Mvc 3 to Mvc 4 and hense Unity.Mvc3 to Unity.Mvc, an single instance is created and used across all web requests, untill restarting the app. Basically, IDummyService is a singleton in a Mvc 4 application when using HierarchicalLifetimeManager. For me this is hard to believe this is intended new behavior in Unity.Mvc.

Is there a better explanations for this?

dimanche 3 mai 2015

Asp.net mvc 4 jquery ajax request return internal server error

i try to establish ajax request to asp.net mvc controller , but it give me internal server error

// My Products Controller
[HttpPost]
    public ActionResult FilterCategeory(string prodID) 
    {
        var categs = new Categ() {PROD_ID=prodID.ToInt32() }.Search();
        return Json(categs, JsonRequestBehavior.AllowGet);
    }

//My ajax request 
$("#categs").empty();
    var prm = $("#prods").val();
    $.ajax({
        type: "POST",
        url: '@Url.Action("FilterCategeory", "Products")',
        contentType: "application/json; charset=utf-8",
        data: {prodID: prm },
        dataType: "json",
        success: function (data)
        {
           alert('Success');
        },
        error: function () { alert('error');}
        });

vendredi 1 mai 2015

Find Method of Entity framework giving error value cannot be null parameter equal to key

I'm using Find method with primary key and It was working properly till now. It is giving above error now. I re installed same version of Entity framework. Could it be because of different version of Entity framework or some other reason? I am able to make it work if I create object and get data instead of using Find. I am using EF 4.3.1.