mardi 25 avril 2017

Configure structure map to scan for all implementations as opposed to convention?

Currently have my structuremap set-up configured to scan for implementations via convention.

So for any dependency on IMyRepo, MyRepo will be looked for.

But how can I resolve IMyRepo to any implementation that doesn't follow that naming convention?

i.e. TotallyDifferentRepoImp : IMyRepo

Sorry - I should clarify, I want this to be automatically registered - i..e I don't want to have to specify each implementation. I want to configure a convention here.

lundi 24 avril 2017

Understanding Properties

As by definition of properties in C# , these are the extension of fields and can be get set. So can we set the properties of an object of a class as well?

class c1{
     public C2 obj {get;set;}
}

dimanche 23 avril 2017

Creating SMS Gateway using asp.net MVC

I m trying to implement my own SMS gateway using asp.net MVC. Please suggest any solution how to start with it.

Thanks in Advance!!

Post form always returning null

I have an application in asp .net mvc 4 as follows:

1.ProductsController.cs

namespace MvcApplication2.Controllers
{
    public class ProductsController : Controller
    {
        //
        // GET: /Products/

        [HttpGet]
        public ActionResult Products()
        {
            List<Product> prList = new List<Product>();
            Product p1 = new Product();
            p1.ProductName = "J & J";
            p1.Price = 40;
            p1.Ratings = 5;
            prList.Add(p1);
            Product p2 =  new Product();
            p2.ProductName = "Himalaya";
            p2.Price = 20;
            p2.Ratings = 2;
            prList.Add(p2);
            return View(prList);

        }

        [HttpPost]
        public ActionResult Products(FormCollection prList,List<MvcApplication2.Models.Product> fg) 
        {
            return View(prList);
        }

    }
}

2. ProductList.cs

namespace MvcApplication2.Models
{


    public class Product
    {
        public string ProductName { get; set; }
        public int Price { get; set; }
        public int Ratings { get; set; }
    }

}

3. Products.cshtml

@{
    Layout = null;

}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Products</title>
    @Styles.Render("~/Content/css")
        @Scripts.Render("~/bundles/modernizr")

    <script src="~/Scripts/jquery-3.2.1.min.js"></script>
</head>
@model IEnumerable<MvcApplication2.Models.Product>
@using (@Html.BeginForm("Products", "Products", FormMethod.Post))
{
<body>
    <div style="width:100%;height:100%;position: relative ">
        <div style="width:100%;top:0px;height:40px;position:relative;background-color:purple">
            <input type="submit" value="Sort price" style="float : right;width:30px;" id="SearchId" />
            @Html.TextBox("Search Box", null, new { @style = "float:right;width:80px "});
            <input type="submit" value="submit" />  
        </div>
        <div id="tableDiv">
            <table id="tableId">
                <tr>
                    <th>Name</th>
                    <th>Price in Rs.</th>
                    <th>Ratings</th>
                </tr>
@foreach (var drawing in Model)
{

                <tr>
                    <td>@drawing.ProductName</td>
                    <td>@drawing.Price</td>
                    <td>@drawing.Ratings</td>
                </tr>

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

Whenever I navigate to http://localhost:5858/Products/Products and click and on submit , the contol comes to [HttpPost] in Products methods, but the model is always empty .

What is it that I am missing here?I am expecting the same model to be returned when the page was loaded , why is it that the model is becoming empty?

jeudi 20 avril 2017

Why does this one DropDownListFor work, and this other one doesnt?

I am trying to learn mvc, and after much struggle I finally got a DropDownListFor to work as intented. Here is the working Dropdownlistfor.

Working ViewModel

public partial class get_preKschedule_Result
    {
        public string start_time { get; set; }
        public Nullable<short> lunch_minutes { get; set; }
        public string dismiss_time { get; set; }
        public Nullable<short> headct { get; set; }
        public byte format { get; set; }
        public Nullable<byte> days_per_week { get; set; }
        public string description { get; set; }
    }

format is the type of preK program the school is enrolled in. The values are stored 1-10 in the database so the DropDownListFor will need all values and text. Here is the View.

Working View

@model  DirectoryMVC.Models.get_preKschedule_Result

@{
    List<SelectListItem> listItems = new List<SelectListItem>();
    listItems.Add(new SelectListItem { Text = "Head Start", Value = "6" });
    listItems.Add(new SelectListItem { Text = "Four Year Old At Risk", Value = "7" });
    listItems.Add(new SelectListItem { Text = "Integrated Special Ed", Value = "8" });
    listItems.Add(new SelectListItem { Text = "Reverse Mainstream Special Ed", Value = "9" });
    listItems.Add(new SelectListItem { Text = "All Other District Special Ed", Value = "10" });

}
<div class="col-md-2">
    @Html.DropDownListFor(m => m.format, new SelectList(listItems, "Value", "Text", listItems.Where(x => x.Value == Model.format.ToString())))
    @*listItems*@
</div>

I don't know if there is an easier way, but this is the way I finally got it to work. So when I do this exact same process for this next ViewModel it didn't work! Edit The administrator dropdown for title is not selecting any value, or setting any text. I will also list everything I tried. I am 100 percent sure that the data returned is correct I have verified in the watch that the models property title evaluates to true when I compare it to SelectListItems value.

Non-Working ViewModel

public partial class get_administrators_Result
{
    public int admin_id { get; set; }
    public string first_name { get; set; }
    public string last_name { get; set; }
    public string title { get; set; }
    public string email { get; set; }
}

Non-Working View

@model  DirectoryMVC.Models.get_administrators_Result

@{ 
    List<SelectListItem> listItems = new List<SelectListItem>();
    listItems.Add(new SelectListItem { Text = "Mr.", Value = "Mr." });
    listItems.Add(new SelectListItem { Text = "Ms.", Value = "Ms." });
    listItems.Add(new SelectListItem { Text = "Dr.", Value = "Dr." });
    listItems.Add(new SelectListItem { Text = "Miss", Value = "Miss" });
    listItems.Add(new SelectListItem { Text = "Mrs.", Value = "Mrs." });
    listItems.Add(new SelectListItem { Text = "Rev.", Value = "Rev." });
}

<div class="col-md-1"> @Html.DropDownListFor(m => m.title, new SelectList(listItems, "Value", "Text", listItems.Where(x=>x.Value == Model.title)))
</div>

I have even tried

@Html.DropDownListFor(m => m.title, new SelectList(listItems, "Value", "Text", Model.title))
@Html.DropDownListFor(m => m.title, new SelectList(listItems, "Value", "Text", (object)Model.title))

and every other combination I can think of with the lambda (m=> m, ...

mardi 18 avril 2017

how to pass model to partialview in umbraco?

I want to pass a object as model to a partial view in umbraco. there is two function @Html.Partial() and @Html.Partial() which have 4 override method listed below :

@Html.Partial(string partialName)
@Html.Partial(string partialName, Object object)
@Html.Partial(string partialName, Object object, ViewDataDictionary dic)
@Html.Partial(string partialName, ViewDataDictionary dic)

and :

@Html.RenderPartial(string partialName)
@Html.RenderPartial(string partialName, Object object)
@Html.RenderPartial(string partialName, Object object, ViewDataDictionary dic)
@Html.RenderPartial(string partialName, ViewDataDictionary dic)

I try to use @Html.RenderPartial(string partialName, Object object) and @Html.Partial(string partialName, Object object) but i an getting this Exception:

Cannot bind source type <>f__AnonymousType0`1[[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]] to model type Umbraco.Web.Models.RenderModel.

I search a lot in google to an example of using these methods but i cannot find any thing. so there are two question:

  1. What is different between Partial and RenderPartial method?
  2. How can I pass data to partialview from page razor?

How to remove the "" part from mvc

An mvc application I'm supposed to maintain doesn't work on FF.I have a site, which shows a pdf inside an <iframe>. When I try run it on FF, it shows me the Corrupted Content Error inside the iframe. The page you are trying to view cannot be shown because an error in the data transmission was detected . After googling a bit it seems it is due to having to many headers inside, so I checked in IE (it works properly on IE), and yeah, this was the frame content:

<object width="100%" height="100%" classid="clsid:......">
    <PARAM NAME="ExtentX" VALUE="25135">
    .... many other PARAM NAMEs>
</object>
<html style="display: none;">
  <head></head>
  <body></body>
</html>

So it appears to solve my problem I have to delete the <head> elements inside the fame. According to my googling it seems the problem is somewhere with the Response.appendHeader functions, but everything seems okay to me. My controller code:

Response.AddHeader("Content-Disposition", "inline; filename=" + fileName + "#toolbar=1&amp;view=FitV");
Response.AppendHeader("Cache-Control", "no-cache, no-store, must-revalidate"); // HTTP 1.1.
Response.AppendHeader("Pragma", "no-cache"); // HTTP 1.0.
Response.AppendHeader("Expires", "0"); // Proxies.

Someone suggested adding those lines before those lines, but it didn't help:

Response.ClearHeaders();
Response.ClearContent();
Response.Clear();

lundi 17 avril 2017

The name 'Url' does not exist in the current context in Areas Folder

I've WebAPI project. I've created Areas for admin panel. I've attached screenshot below for project structure.
enter image description here

In web.config of Areas->Views folder, I've mentioned:

<system.web.webPages.razor>
    <host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
    <pages pageBaseType="System.Web.Mvc.WebViewPage">
      <namespaces>
        <add namespace="System.Web.Mvc" />
        <add namespace="System.Web.Mvc.Ajax" />
        <add namespace="System.Web.Mvc.Html" />
        <add namespace="System.Web.Routing" />
        <add namespace="System.Web.Optimization" />
        <add namespace="CallApp" />
      </namespaces>
    </pages>
  </system.web.webPages.razor>

In Web.Config of root folder, I've mentioned:

<appSettings>
<add key="webpages:Version" value="3.0.0.0" />
<add key="webpages:Enabled" value="false" />
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />

But I am getting The name 'Url' does not exist in the current context error in _Layout.cshtml page of Areas Admin.
enter image description here

jeudi 13 avril 2017

Custom Remote Valdaition Without MVC Reference In DataModel class

[CustomRemote("Error Message", Action = "ActionName", Controller = "User", AdditionalFields = ".UserId,.RoleId")] public string UserName { get; set; }

mercredi 12 avril 2017

Regex Visual Studio One Specific Character

I am trying to validate a text box in Visual Studio to be either the character M or F. I have a few other validations with regex set in a similar fashion which are all working correctly. However, with this one, it still allows me to use ANY letter in the text box. What is wrong with this code?

public static bool IsGender(string gender)
{
    bool validGender = true;
    string _genderRegEx = @"^\:|m|M|f|F|$";
    if ((!Regex.Match(gender, _genderRegEx).Success))
    {
        MessageBox.Show("Gender must be either M or F.");
        validGender = false;
    }
    return validGender;
}

How to mask Password in MVC ViewRazor

I need to mask Password in View in MVC Project, where i have list of users.

I have this code in View, where i see the password at the moment.

 @Html.DisplayFor(modelItem => item.Password)

How to Mask password in View?

mvc images in_Layout.cshtml missing in some of my views

In my _Layout.cshtml, I have the main section for the views as shown below:

@RenderBody()

It properly set background image for create views.For Example CADCreate.cshtml But misses the backrground image for edit and delete views. For example CADEdit.cshtml and CADDelete.cshtml.

Note :

  • All views mentioned above, except Layout.cshtml, are in the same folder.

  • The images folder is under my project folder.

Thanks in advance

MVC Routing with Period in parameter name

I am trying to implement a remote validation using entity framework in an MVC application. I need help trying to define the action signature and the appropriate route config. I have the following class in my model:

 public class FiscalReports
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public long id { get; set; }
    public Int64 Counter { get; set; }
    public short FiscalYear { get; set; }
   [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:MMM dd, yyyy}")]
   [DisplayFormat(DataFormatString = "${0:N0}")]
    [Remote("ValidateSalary", "FiscalReports", AdditionalFields ="Counter, FiscalYear")]
    public int? Salaries { get; set; }

}

I have a viewmodel which is used for a view that contains several of the above objects.

 public class FiscalReportVM
{
    public FiscalReports CurrentFR { get; set; }
    public FiscalReports ReportedToDate { get; set; }
    public FiscalReports BudgetToDate { get; set; }
}

The Validation action is in the FiscalReports controller is as follows:

  public JsonResult ValidateSalary(int Salaries, short FiscalYear, int Counter)
    {
        return ValidateFiscalField(Salaries, FiscalYear, Counter, "Salaries");
    }

In the view I am using the HTML helper

@Html.EditorFor(model=>model.CurrentFR.Salaries)

This generates the field and validation correctly. Generated HTML is below

input data-val="true" data-val-number="The field Salaries must be a number." data-val-remote="'Salaries'; is invalid." data-val-remote-additionalfields="*.Salaries,*.Counter,*.FiscalYear" data-val-remote-url="/FiscalReports/ValidateSalary" name="CurrentFR.Salaries" type="number" value="" />

The validation request is firing properly and in fiddler I see the following request:

http://localhost:50409/FiscalReports/ValidateSalary?CurrentFR.Salaries=27000&CurrentFR.Counter=4773&CurrentFR.FiscalYear=2

My problem is that I have trouble defining a route and action with the variables in dotted notation. The action definition does not accept dotted parameters (Can't do ValidateSalary(int CurrentFR.Salaries,....). I need help trying to define the action signature and the appropriate route config.

mardi 11 avril 2017

Store current date and time in database using MVC

I have a requirement where I need to store the current system time in the database. here I need to provide 2 logins for User and Admin. Here User will login into the application and will click the In button. Then button action will trigger and will load the current system date and time and it will be saved in the database as well. same like Out button too. Below are the code works which I did,

This is my Model,
public class Employee
    {
        public DateTime In { get { return DateTime.Now; } }
        public DateTime Out { get; set; }
        public string Name { get; set; }
        public string Email { get; set; }
        public string Password { get; set; }
    }
}

This is My controller,
public ActionResult Login(Employee ED)
        {
            if (ModelState.IsValid)
            {
                var Admin = DE.tblEmployees.Where(m => m.Email.Equals(ED.Email) && m.Password.Equals(ED.Password)).Select(a => new { a.Role, a.Name, a.Email }).ToList();
                if (Admin != null)
                {
                    var role = Admin[0].Role;
                    ViewBag.Email = Admin[0].Email;

                    if (role == "Admin")
                        return RedirectToAction("AdminView", "Home");
                    else
                        return RedirectToAction("UserView", "Home");
                }
            }
            return View();
        }

This is My View,
        <button type="button">In</button>
        <button type="button">Out</button>

when you click In button then automatically current system date and time will save automatically.
How to achieve that functionality, how to write the code for this..
Any help would be grateful.

Failed to load pdf document in Mvc Using ITextSharp

Hi this is my Controller code for generate PDf

using System.Web;
using System.Web.Mvc;
using B2B.Common.Models;
using B2B.Common;
using System.Web.Security;
using B2B.BAL;
using iTextSharp.text;
using System.IO;
using iTextSharp.text.html.simpleparser;
using iTextSharp.text.pdf;
using System.Text;

namespace B2B.UI.Areas.Agency.Controllers
{
    [Authorize(Roles = RolesType.Agent)]
    public class MyBookingController : Controller
    {

        #region Hotels Booking
        public ActionResult HotelsBooking()
        {


            StringBuilder pdfBody = new StringBuilder();
            pdfBody.Append("<div class='col-sm-10 dashboard_right_cont pt-2 pb-2' style='margin-bottom:-60px;'>");
            pdfBody.Append("<div id='bookingDetails'  class='registration_cont'>                               ");
            pdfBody.Append("<h4 class='text_blue'><strong>Booking Details</strong> </h4>                       ");
            pdfBody.Append("<hr class='hr_blue'>                                                               ");
            pdfBody.Append("<div class='row'>                                                                  ");
            pdfBody.Append("<div class='col-sm-3'>                                                             ");
            pdfBody.Append("<div class='alert alert-success'>                                                  ");
            pdfBody.Append("<p class='mb-1'>Booking reference number:</p>                                      ");
            pdfBody.Append("<h5><strong>@Html.DisplayFor(model => model.BookingRefNo)</strong></h5>            ");
            pdfBody.Append("<hr class='mt-1 mb-1'>                                                             ");
            pdfBody.Append(" <p class='mb-1'>Booking status:</p>                                               ");
            pdfBody.Append(" <h5><strong>@Html.DisplayFor(model => model.Status)</strong></h5>                 ");
            pdfBody.Append("</div>                                                                             ");
            pdfBody.Append("<div class='alert alert-info'>                                                     ");
            pdfBody.Append("<h6><strong><i class='fa fa-user'></i> Leading Passenger</strong></h6>             ");
            pdfBody.Append("<p class='mb-1'>Passenger name:</p>                                                ");
            pdfBody.Append("<h6><strong>@Html.DisplayFor(model => model.LeadingPassengerName)</strong></h6>    ");
            pdfBody.Append(" <hr class='mt-1 mb-1'>                                                            ");
            pdfBody.Append(" <p class='mb-1'>Nationality:</p>                                                  ");
            pdfBody.Append(" <h6><strong>India</strong></h6>                                                   ");
            pdfBody.Append("  <hr class='mt-1 mb-1'>                                                           ");
            pdfBody.Append("  <p class='mb-1'>Country of residence:</p>                                        ");
            pdfBody.Append("  <h6><strong>India</strong></h6>                                                  ");
            pdfBody.Append("</div>                                                                             ");
            pdfBody.Append("<hr>                                                                               ");
            pdfBody.Append("</div>");



            pdfBody.Append(" </div>                                                                                                                                                                                  ");
            pdfBody.Append(" </div>                                                                                                                                                                                  ");
            pdfBody.Append(" <div class='col-sm-12'>                                                                                                                                                                 ");
            pdfBody.Append(" <div class='hotel_search_details_cont bg_white'>                                                                                                                                        ");
            pdfBody.Append("  <p class='mb-1'>Check-in:</p>                                                                                                                                                          ");
            pdfBody.Append("  <h6><strong>11 Apr 2017 10:30:00</strong></h6>                                                                                                                    ");
            pdfBody.Append("  <hr class='mt-1 mb-1'>                                                                                                                                                                 ");
            pdfBody.Append("  <p class='mb-1'>Check-out:</p>                                                                                                                                                         ");
            pdfBody.Append("  <h6><strong>11 Apr 2017 10:30:00</strong></h6>                                                                                                                      ");
            pdfBody.Append("  <hr class='mt-1 mb-1'>                                                                                                                                                                 ");
            pdfBody.Append("  <p class='mb-1'>Room type:</p>                                                                                                                                                         ");
            pdfBody.Append("  <h6><strong>Sperior</strong></h6>                                                                                                                ");
            pdfBody.Append("  <hr class='mt-1 mb-1'>                                                                                                                                                                 ");
            pdfBody.Append("  <p class='mb-1'>Room occupancy:</p>                                                                                                                                                    ");
            pdfBody.Append("  <h6><strong>2 Adults</strong></h6>                                                                                                                                                     ");
            pdfBody.Append("  <hr class='mt-1 mb-1'>                                                                                                                                                                 ");
            pdfBody.Append("  <p class='mb-1'>Bedding preference:</p>                                                                                                                                                ");
            pdfBody.Append("  <h6><strong>No preference</strong></h6>                                                                                                                                                ");
            pdfBody.Append("  <hr class='mt-1 mb-1'>                                                                                                                                                               ");
            pdfBody.Append("  <p class='mb-1'>Rate basis:</p>                                                                                                                                                        ");
            pdfBody.Append("  <h6><strong>Breakfast</strong></h6>                                                                                                                                                    ");
            pdfBody.Append("  <hr class='mt-1 mb-1'>                                                                                                                                                                 ");
            pdfBody.Append("                                                                                                                                                                                         ");
            pdfBody.Append("  <p class='mb-1'>Additional requests:</p>                                                                                                                                               ");
            pdfBody.Append("  <h6><ol><strong><li>Request for an early check in</li> <li>Request for an late check out</li> <li>Please note that guest is a VIP</li></strong></ol></h6>                              ");

            pdfBody.Append(" </div>   ");
            pdfBody.Append(" </div>   ");
            pdfBody.Append(" </div>   ");
            pdfBody.Append(" </div>   ");
            pdfBody.Append("</div>    ");
            pdfBody.Append("</div>    ");
            pdfBody.Append("</div>    ");
            string pdfContent = Convert.ToString(pdfBody);


            Document document = new Document();         
            document.Open();
            StyleSheet styles = new StyleSheet();
            HTMLWorker hw = new HTMLWorker(document);
            hw.Parse(new StringReader(pdfContent));
            document.Close();
            Response.ClearContent();
            Response.ClearHeaders();
            Response.ContentType = "application/pdf";
            Response.AddHeader("Content-Disposition", "attachment;filename=PrintVoucher.pdf");
            Response.Flush();
            Response.Clear();




            return View();
        }


    Pdf is downloaded but it shows failed to load pdf document.

I didn't find where I mistake in code.

Please give me correct code Pdf is downloaded but it shows failed to load pdf document.

I didn't find where I mistake in code.

Please give me correct code

Thanks.

lundi 10 avril 2017

Setting data filters in partial views

I need a little help. So I'm trying to call a lot of partial views from the same list model, each using a different filter. Is there anyway for me to pass the Datafilter value from the views into the model?

vendredi 7 avril 2017

how to get access to some files for some users in mvc asp application?

i'm trying code a website which is like youtube.com but some videos are premium and users must pay to get access to those videos , my problem is => my videos are available for all users and if someone would have the address of that video can download that without logging to my website . i want to let some parts of users to download that . I've tried changing video names after a short while but it has it's own problems :'( is there any way that i give some sessions access permission for downloading a file ? <3 thanks for your help

mercredi 5 avril 2017

StackOverflow exception at the end of a webservice (No recursion / infinite loop) [ASP.NET App]

First of all, I would like to apologize if my language is not the best, I'm acutally not english.

To begin with, I work in a company and I'm maintaining an ASP.NET MVC 3.0 application. Recently the client which I'm working for, submitted a report telling that when he validate a certain page (I will describe how it works later), the app was saving the values but returned an error page.

After a few research, I found out that the application was getting a StackOverflow Exception at the end of the webservice's call. This exception is occuring in mscorlib.dll.

The problem doesn't happen everytime, it only happens when there is a lot of products related to the one validated in the page.

I tried to use WinDbg to get more information about the StackOverflow Exception but it didn't really helped me... The first warning I caught was this picture.

If you have any questions or informations, feel free to tell me.

site developed using orchard cms shows blank pages frequently in live enviroment

i have developed the site in orchard cms by using asp .net mvc.It works fine for some time and then starts giving blank page.when i recycle the application pool then again site starts working fine and then after some time it shows blank page.this happens every day many times. can any body tell me the proper solution for this.

mardi 4 avril 2017

Display Values based on dropdown selection MVC

I have a requirement which I need to display details based on drop down selection. These details coming from database. when I click one user all then all the details belong to that user has to be displayed. This is my Model, public class TaskDetails { public string ProjectID { get; set; } public string ProjectName { get; set; } public DateTime StartDate { get; set; } public DateTime EstimatedDate { get; set; } public string TaskDescription { get; set; } }

This is My Controller,
            List<SelectListItem> query = DE.tblEmployees.Select(c => new SelectListItem { Text = c.Name, Value = c.Name }).ToList();
            ViewBag.Categories = query;
            return View();

This is My View,
<div class="dropdown">
        @Html.DropDownList("CategoryID", (List<SelectListItem>)ViewBag.Categories, "--User Name--")
    </div>

In the View I am loading all the user values inside the drop down. But when admin selects any of the user then all the details of user has to be displayed under a table. Upto here I am perfect but from here got strucked. How to move forward how to show the details of the user based on dropdown selection.

How to create an AngularCli application that contains another AngularCli inside?

I have an application in development that is in Angular2 using AngularCli, and I want to use it as a "Layout" (like a MasterPage) to another project. Like a big "SPA System".

For example, in the menu we will have the following:

  • Framework
    • Page A
  • Xpto
    • Page B

The Framework is running in http://localhost:90 and XPTO is running in http://localhost:91. Both of them is running on AngularCli.

I want to create a structure that when I click on Page A or Page B, the browser doesn't reload and it will give an "app" style to the user, loading the page as a SPA ACROSS the sites.

The main reason is to reuse the Javascripts, CSS and many other files from de "Framework" project to other 20 projects. I don't want to replicate all the components, files and etc across those projects.

Today we use MVC3 and the RazorGenerator to create .cshtml as a DLL to reuse the .cshtml from Framework to other modules.

But we want go AngularCli. Is there any way to do that ? If it isn't, is there some way to create a template in AngularCli that can be reused the components and the other files ?

Thank you !

How to refresh layout alone in MVC?

I want to refresh layout alone in MVC. I am binding layout menus from session. Whenever session is updated, I want to just refresh the layout for menu update.

Can't POST an array of string to ASP.NET MVC3

I have an MVC3 controller action:

public ActionResult DoStuff(DoStuffModel model)

The DoStuffModel looks like this:

public class DoStuffModel
{
    public long SomeId { get; set; }
    public List<string> Codes { get; set; }
}

In my jQuery I do this:

 var postData = {
     SomeId: 1,
     Codes: ["code1", "code2", "code3"]
 };

$.post(url, postData, function (data) {});

The URL is correct. The postData looks like this when I log it:

enter image description here

The SomeId gets bound correctly, but Codes remains null. What is going on?

How to display details from database to the single user in mvc

I am trying to get the details from database to display in the View. Here I need to display the records for particular user who logged currently. But unfortunately all the data which ever in DB table coming into the view. But I dont want to display all the data.

In DB I have two tables for tblEmployee and TaskDetails This is My Model, public class TaskDetails { public string ProjectID { get; set; } public string ProjectName { get; set; } public DateTime StartDate { get; set; } public DateTime EstimatedDate { get; set; } public string TaskDescription { get; set; } }

    This is My controller,
To fetch the data here I am using ADO.Net,
            public ActionResult TaskDetails(string td)
            {           
                string connectionstring = "data source = NLTI37; initial catalog = Data; integrated security = True; MultipleActiveResultSets = True; App = EntityFramework";
                string sql = "select * from TaskDetail";
                SqlConnection conn = new SqlConnection(connectionstring);
                SqlCommand cmd = new SqlCommand(sql, conn);
                var Details = new List<TaskDetails>();
                { 
                    conn.Open();
                    SqlDataReader rdr = cmd.ExecuteReader();
                    while (rdr.Read())
                    {
                        var ProjectDetail = new TaskDetails();
                        ProjectDetail.ProjectID = rdr["ProjectID"].ToString();
                        ProjectDetail.ProjectName = rdr["ProjectName"].ToString();
                        ProjectDetail.StartDate = DateTime.Parse(rdr["StartDate"].ToString());
                        ProjectDetail.EstimatedDate = DateTime.Parse(rdr["EstimatedDate"].ToString());
                        ProjectDetail.TaskDescription = rdr["TaskDescription"].ToString();
                        Details.Add(ProjectDetail);
                    }
              }
                return View(Details);
            }
    Here I am using ADO.Net to fetching the details. And these details I need to display on the View for user who currently logged in.

    This is my View,
    <tbody>
                    @foreach (var ProjectDetail in Model)
                {   
                        <tr>
                            <td>@ProjectDetail.ProjectID</td>
                            <td>@ProjectDetail.ProjectName</td>
                            <td>@ProjectDetail.StartDate</td>
                            <td>@ProjectDetail.EstimatedDate</td>
                            <td>@ProjectDetail.TaskDescription</td>
                        </tr>
                    }
                </tbody>

Here I need to display the records of the user who loggedin currently. But unfortunately all the user details I am getting here. As per my understanding SQL statement is wrong. Correct Me if wrong. How to get the details for that particular user details.  Can any one help on this.

Bind values from database to dropdown in MVC with Entity frame work

I am trying to bind a value from database to the dropdown in View.

I have a requirement that I need to display database values in dropdown list in a view. I am trying to bind the Email id to the dropdown from the database table.

Here I need to add the Email ID to the dropdown. This is my Model,

public class UserDetails
{
      public List<SelectListItem> Userdetails { get; set; }
      public string Email { get; set; }
}

This is My Controller,

public ActionResult Admin()
{
            var db = new DataEntities1();
            var query = db.tblEmployees.Select(c => new { c.Email });
            ViewBag.Categories = new SelectList(query.AsEnumerable(), "CategoryID", "CategoryName");
            return View();
}

This is my View,

   @model List<MVC_Sample.Models.UserDetails>

             <div class="dropdown">
               @Html.DropDownList("CategoryID", (SelectList)ViewBag.Categories, "--Select One--")

                </div>

View will be loaded with dropdown and the values from database. But unfortunately, I am not able to add the values to drop down. I dono where I did the wrong here. Can anyone help me on this..

lundi 3 avril 2017

Get database Value in textboxFor in bootstrap modal popup in MVC

I place a text box in the bootstrap modal popup and also I have a kink in the table data in the table come from database so I want when I click pop-up show database cell value in the textbox that exists in the modal-popup. Below is my code

Thats my action method that gets data and data is passing to the ViewBag.Type

public JsonResult LinkButton(int RoelID)
{
    Role model = new Role();
    Session["State"] = RoelID;
    int id = RoelID;
    RoleServices ser = new RoleServices();
    var data = ser.Get(id);          
    bool result=false;
    if(Session["State"]!=null)
    {
        ViewBag.Type = data.RoleType;
        result=true;
    }
    return Json(result, JsonRequestBehavior.AllowGet); 
}

Here is a code of JQuery and Ajax acall the action method on link click

<a href="#"  onclick="UpdateID(@item.RoelID)">Select</a>

<script>
    var UpdateID = function (RoelID) {
        $("#hiddenID").val(RoelID);
        var roleID=$("#hiddenID").val();
        $.ajax({
            type: "post",
            url: '@Url.Action("LinkButton", "Account")',
            data: { RoelID: roleID },
            success:function()
            {
                $("moReg").modal('hide');
            }
        })
        $("#moReg").modal('show');
    } 
</script>

Here is textBox in the Modal PopUp

@Html.TextBoxFor(model => model.RoleType, new { @value=ViewBag.Type })