I am using Razor Syntax. In my issue scenarion, I have a select dropdown, And when the user selects empName, a Pop Up opens. In this Popup I call a method with Razor which takes 2 parameters. the 2nd parameter is the empName(value selected in select dropdown).

How to pass this selected value as a 2nd parameter?

<select id="empName">
    <option value="">--Select--</option>
      <option>A</option>
      <option>B</option>
      <option>C</option>
</select

HTML of Pop Up Dialog, Which opens when User selects & clicks Open PopUp Btn.

<div>
    @foreach (var item in new obj.getMasterFields('Category', par2))
    {
         <label for="@item.Key">@item.Value</label> <br />
         ....
    }
</div>

Note : The Popup is Twitter Bootstrap Modal opened with Jquery.

I have a routing as per below

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

Now for the id part, I'm combining many sets of data delimited by "-" character and the encrypt it with AES (RijndaelManaged) encryption. And the I UrlEncode it and send to someone email as per below...

http://localhost:7777/Product/Invite/%e3%b7%92%e4%97%ad%eb%b6%b3%e3%b7%90%eb%b2%8c%e2%aa%ad%e7%86%87%e9%b6%9e%ec%ae%aa%ec%a7%a2%ec%9a%a0%ec%ba%be%e2%89%bc%e5%ba%aa%ee%be%a8%ee%9f%a8%ea%aa%b6%e3%87%83%e3%8c%b4%eb%99%89%e8%8f%bb%e4%b0%ab%ef%bf%bd%e7%a0%99

but upon clicking it I'm getting error.

Bad Request - Invalid URL

HTTP Error 400. The request URL is invalid.

Below is the encryption and encoding process

 string data1 = email.EmailID + "  - /" + events.EventID + "-" + DateTime.Now.ToString("yyyyMMddhhmm") + "-" + events.MemberID;

 var encoding = new UTF8Encoding(false, true);
 byte[] cypherBytes = advEncryProvider.Encrypt(encoding.GetBytes(data1));
 string dataEncodedString = HttpUtility.UrlEncode(GetString(cypherBytes));

Tried editing web.config as How do I enable special characters in MVC routing?

but still no luck

 <system.web>
<httpRuntime targetFramework="4.5" requestPathInvalidCharacters="" requestValidationMode="2.0"/>
<compilation targetFramework="4.5" debug="true"/>
<pages validateRequest="false">
  <namespaces>
    <add namespace="System.Web.Helpers"/>
    <add namespace="System.Web.Mvc"/>
    <add namespace="System.Web.Mvc.Ajax"/>
    <add namespace="System.Web.Mvc.Html"/>
    <add namespace="System.Web.Optimization"/>
    <add namespace="System.Web.Routing"/>
    <add namespace="System.Web.WebPages"/>
  </namespaces>
</pages>

This morning I woke up discovering that my MVC 4 web application on my server had broken.

The error message is: An exception of type 'System.IO.FileNotFoundException' occurred in mscorlib.dll but was not handled in user code. Additional information: Could not load file or assembly 'Newtonsoft.Json, Version=4.5.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed' or one of its dependencies. The system cannot find the file specified.

I opened my VS project and ran it from code (so on a different computer), same error occurred!

I checked my server log and discovered updates were automatically installed at 5:06 AM. One of the updates was done by an installer package AspNetMVC4.msi. One minute later, the first errors on my web application began streaming in.

On my development laptop, the same installer had run yesterday (Oct 15) at 1:10:10 PM.

Same problem on both computers.

I had never heard of Newtonsoft.Json (but now I found out what it is). It looks as if one of the MVC dlls (unlikely) or one of the package dlls (more likely) has a reference to Newtonsoft.

I have tried to intall Newtonsoft from nuget. This did have some effect, the error changed from FileNotFound to a FileLoadException:

An exception of type 'System.IO.FileLoadException' occurred in mscorlib.dll but was not handled in user code Additional information: Could not load file or assembly 'Newtonsoft.Json, Version=4.5.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)

I also tried to upgrade from .NET 4.5 to 4.5.1. That did not help.

BTW, the error occurs in RegisterRoutes in Global.asax.cs:

routes.MapHttpRoute( 
    name: "DefaultApi",
    routeTemplate: "api/{controller}/{id}",
    defaults: new { id = RouteParameter.Optional }
);

Any ideas?

I want get Latitude and Longtitude when i click and set a marker on google map on mvc and send them to my action in controller in a form.

I found an article about this, but it is for .Net Web Form.

https://tr.scribd.com/doc/234445435/Google-Maps-API-Ile-Web-Sayfalar%C4%B1nda-Harita-Kullanmak-Yazilimgunlugu

Simply , i have a form (for data post to action). In this form 4 area (Title,Picture,Lat,Long ). I am using MVC5. How can I do it?

Scenario is :

"User writes Title, selects Picture, click on the map wherever wants - and a marker appears on map- he/she can drag/move marker somewhere on map if wants to change marker point. Finally user submits form. 4 data elements gone to action"

I am using Reflection to get values on basis of specified dynamic column name(model property).

My issue is when i pass propName, it is in All Caps, if i convert it in LowerCase(), still it doesn't match with the Model property.

Here is Code :-

public object GetPropValue(object obj, string propName)
{
     return obj.GetType().GetProperty(propName).GetValue(obj, null);
}


 var Fields = obj.GetPropValue(Employee, item.Key);  // item.key = 'ADDRESS'

public class Employee
{
      public string Address { get; set; }
      ....
}

What is solution for this?

Short question

In a web content manager (controller+model) that has two posibles customizations:

  • Plugins (model): that allow to add content types, for example an image gallery.
  • Skins (view): Allow to implement different appearance for the web.

Ideally, a plugin do not know about the skin and the skin do not know about the plugin, so the page manager should get data from the plugin and pass it to the skin which show the page correctly. That does not seem possible, but I would like to let them as separated as possible.

How to deal with the plugin and the skin so they may work together?

Possibles ideas:

1) Implement a specific joint for every plugin * skin combinations

For every combination of plugins and skin, implement a small code that add the appearance for the plugin info to the skin. As an example, the skin may contain a folder with each "joint".

This solution carry that a skin without a joint for a specific plugin cannot represent it.

2) Implement a default plugin skin, and let the skin to use it or implement a new appearance:

  1. The controller get the info from the plugin and also a function pointer to generate a default skin for it.
  2. The controller call the skin which may implement his own appearance or just call the default appearance of/for the plugin.

enter image description here

This solution has a few conceptual errors: the plugin has to implement a skin (Part of the view is into the model code).

There is probably a lot of others possibilities.

Summary question

I am looking for a (good) architectural solution to allow plugins (part o the model) to add features, and skins (View) to add the appearance: more specifically, how to allow the skin to show the plugin content without mixing the code of the Model and the View?

I am using Razor Syntax. In my issue scenarion, I have a select dropdown, And when the user selects empName, a Pop Up opens. In this Popup I call a method with Razor which takes 2 parameters. the 2nd parameter is the empName(value selected in select dropdown).

How to pass this selected value as a 2nd parameter?

<select id="empName">
    <option value="">--Select--</option>
      <option>A</option>
      <option>B</option>
      <option>C</option>
</select

HTML of Pop Up Dialog, Which opens when User selects & clicks Open PopUp Btn.

<div>
    @foreach (var item in new obj.getMasterFields('Category', par2))
    {
         <label for="@item.Key">@item.Value</label> <br />
         ....
    }
</div>

I have error in this code:

<a href="@Url.Action("Settings", new { ViewBag.IsView = true })" class="btn">View</a> 

Can I set in ViewBag.IsView property true?

ViewBag.IsView is declared just in this scope nowhere else.

I have a requirement of importing data from excel to database table. The excel file has the following data.

enter image description here

Block can be NULL. All other field must have data.

I have 4 tables

  1. dbo.Building [BuildingID, Building]
  2. dbo.Block [BlockID, Block, BuildingID]
  3. dbo.Apartment [ApartmentID, Apartment, BuildingID, BlockID]
  4. dbo.RoomNo [RoomNoID, RoomNo, ApartmentID]

each table has id as primary key which is identity. Block contain Building ID as foreign key Apartment contain Building ID and Block ID as foreign key Room No contain Apartment ID as foreign key

I need to import the data from excel to these related table with correct relation.

I successfully imported the data from Excel to a single table. How can i insert excel data to these related table

I've a .net application from where I'm using token based external authentication in JasperReports. I'm facing an issue while logging out from my application, when I logged out from my .net application it should automatically log out from JapserReports also.

Please assist me in controlling behavior of log out functionality of JasperReports. I mean if by any way I can kill the session of JasperReports as soon as user logged out from .net application.

I basically did nothing. Just opened Visual Studio 2012(Ultimate). Created new ASP.NET MVC 4 web application (using Razor Engine). Clicked the green "Run" button - but when it launches exceptions like this are shown on Output window:

"A first chance exception of type 'Microsoft.CSharp.RuntimeBinder.RuntimeBinderException' occurred in Microsoft.CSharp.dll"

and Google chrome seems to become unresponsive.

When I clicked Run in Internet Explorer, I got this message:

enter image description here

This question already has an answer here:

So, I have this link:

<li><a id='HomeLink' href="#" style="font-size:large" onclick="loadPartialHome();alert('huzza!');">Receitas</a></li>

And the corresponding function:

$(document).ready(function () {
        function loadPartialHome() {
            $.get('@Url.Action("IndexPartial","Home")', function (data) {
                $('#partialLoader').html(data);
                $('#partialLoader').fadeIn();
            });
        }
    });

Why is it not working? If I take the function call off of the onclick event, the alert displays the message, but if the function is there, it doesnt get to it. I tried debugging it but it never reaches the controller. What is wrong with this code?


Just to be clear, I tried using global function and a proper event handler, and it didn't work.

I have this code in HomeController that should return the last 6 rows.

private List<SelectListItem> GetOriginalIDs(string thisPWS)
{
    List<SelectListItem> list = new List<SelectListItem>();

    var cat = (from c in _db.DWS_BactiBucket.OrderByDescending(x => x.SampDate) 
               where  c.PWS == thisPWS && c.SampType  == "R" && c.IsTOTPresent  == "1" select c).Take(6).ToArray();

    for (int i = 0; i < cat.Length; i++)
    {
        list.Add(new SelectListItem { Text = cat[i].LabSampID + " (" + cat[i].SampDate + ")", Value = cat[i].LabSampID.ToString() });
    }

    return list
}

I want to run this code to populate a 2nd pulldown based on what was selected in the 1st pulldown(I'll bet you've never heard of this one before).

Here is the 1st pulldown on the Add View:

<div class="editor-field">
    @{
        var listItems = new List<SelectListItem>();
        listItems.Add(new SelectListItem{Text="", Value=""});                
        listItems.Add(new SelectListItem{Text="R", Value="R"});
        listItems.Add(new SelectListItem{Text="P", Value="P"});                
        listItems.Add(new SelectListItem{Text="C", Value="C"});
        listItems.Add(new SelectListItem{Text="T", Value="T"});
        listItems.Add(new SelectListItem{Text="A", Value="A"});   
        listItems.Add(new SelectListItem{Text="S", Value="S"});                

        }

    @Html.DropDownListFor(m=>m.SampType, listItems)

</div>

This all shows up fine and dandy. Here is the second pulldown:

        <div class="editor-field">

            @Html.DropDownListFor(model => model.OrigSampID(IEnumerable<SelectListItem>)ViewBag.Originals)
   })

         </div>

The goal is to populate the 2nd one using JSON and or jQuery but I cannot wrap my head around the code syntax for calling the controller and filling the 2nd pulldown. All examples have not helped me.

Is there a way to put multiple data-role into a razor code? I need it to tag my select list for a jquery tagger.

I need to make following:

@Html.DropDownList("Orientations", (SelectList)ViewBag.Orientations, "None", new { @multiple data-role="tagsinput", @class = "form-control" })

from:

@Html.DropDownList("Orientations", (SelectList)ViewBag.Orientations, "None", new { @class = "form-control" })

But it does not work by that way.
Thank you!

I want every person that registers in my website to be added to a default role "Users", question is how do I do it? :D

This is my register.aspx code:

<%@ Page Title="" Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true" CodeFile="register.aspx.cs" Inherits="register" %>

<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
    <form id="register1" runat="server"><center><b><asp:CreateUserWizard ID="CreateUserWizard1" runat="server" 
  ContinueDestinationPageUrl="~/default.aspx" AnswerLabelText="תשובה סודית:" 
        CompleteSuccessText="המשתמש נוצר בהצלחה!" 
        ConfirmPasswordCompareErrorMessage="הסיסמאות חייבות להיות שוות." 
        ConfirmPasswordLabelText="וודא סיסמא:" CreateUserButtonText="הירשם" 
        EmailLabelText="כתובת דואר אלקטרוני:" PasswordLabelText="סיסמא:" 
        QuestionLabelText="שאלה סודית:" UserNameLabelText="שם משתמש:">
  <WizardSteps>
    <asp:CreateUserWizardStep ID="CreateUserWizardStep1" runat="server" Title="הרשמה">
    </asp:CreateUserWizardStep>
    <asp:CompleteWizardStep ID="CompleteWizardStep1" runat="server">
    </asp:CompleteWizardStep>
  </WizardSteps>
</asp:CreateUserWizard></b></center></form>
</asp:Content>

Thanks to anyone who helps!! :)

I've just started with MVC after working on Web Forms for 4 years. I've watched few videos explaining the architecture/fundamentals and I'm now able to replicate few modules of my old project with MVC5 using EF6.

I've a SQL Server DB containing tables such as Albums/Artists/Titles/Reviews and he User Table. I was able to work with the first set of tables using EF6 just fine including inserts/deletes. The prev project I had implemented custom Web Forms authentication using BCrypt by storing the details in the User table and later doing the validations and setting the auth cookie.

User table has details such as UserId, PWHash, EMail, FirstName, LastName. The UserId is a FK in the Reviews table and few others.

The implementation I'm hoping for is as below:

  1. Login screen accepts credentials and validates with existing User table.
  2. If valid, move to the 2FA screen(eMail/SMS).
  3. If valid, then allow access to application.

Most of the tutorials say how to extend the attributes such as FirstName/LastName but do not say how to use an existing DB. I'm planning to use bcrypt/scrypt to encrypt the sensitive details.

I've gone through MVC 5 & ASP.NET Identity - Implementation Confusion but id doesn't have all the answers to my queries

While debugging using IISExpress, I'd love to save the emails the program sends to a local folder. To do this I have tried to add this to my web.config:

  <system.net>
    <mailSettings>
      <smtp deliveryMethod="specifiedPickupDirectory"   from="blah@example.com">
        <specifiedPickupDirectory
          pickupDirectoryLocation="c:\foo\"
        />
      </smtp>
    </mailSettings>
  </system.net>

I then use the following:

    SmtpSection section = (SmtpSection)ConfigurationManager.GetSection("system.net/mailSettings/smtp");
    using (System.Net.Mail.MailMessage MyMessage = new System.Net.Mail.MailMessage())
    {
        MyMessage.To.Add("hi@example.com");
        MyMessage.From = new MailAddress("test@example.com");
        MyMessage.Subject = "Hi Welcome to test. ";
        MyMessage.Body = "message here yo";
        MyMessage.IsBodyHtml = true;
        using (System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient())
        {
            smtp.DeliveryMethod = section.DeliveryMethod;
            smtp.Send(MyMessage);
        }
    }   

Unfortunately, section is always contains the default mail settings. For example, using the debugger, I can see that its delivery method is always "network" instead of the specifiedPickupDirectory value I'd expect and other values like "from" are null as if it never read anything.

Thanks in advance for any insight

In visual studio I have a formview that displays 2 different sets of data from a table in sql dependant on what paging number the user clicks on. 2 of those data types are hyperlinks that are currently only showing the actual link, not a clickable link. What can I do?

Code in SQL

Create table FBUser
(
[ID] bigint not null,
Photo Varchar(333) not null,
Name Varchar(333) not null,
[Description] Varchar(333) not null,
[Joined on] Datetime not null,
HomeTown varchar(333) not null,
Affiliation varchar(333) not null,
[Current Location] varchar(333) not null,
Gender varchar(333) not null,
[Email address] varchar(333) not null,
[Other accounts] varchar(333) not null,
[Personal Website] varchar(333) not null,
[Total Likes] bigint not null,
[Party Logo] Varchar(333) not null
Primary key ([ID])
)

Insert into FBUser
Values
('612831408762037', 'David1.png', 'David Cunliffe', 'Ex-Labour Leader', '12-Feb-2009', 'New Lynn', 'New Zealand Labour Party', 
'New Lynn', 'Male', 'david.cunliffe@parliament.govt.nz', 'David Cunliffe', 'http://labour.org.nz/davidcunliffe', '1', 'Labour.jpg'),

('1119736203', 'John.jpg', 'John Key', 'Prime Minister', '20-Feb-2009', 'Auckland', 'New Zealand National Party', 
'Auckland', 'Male', 'j.key@ministers.govt.nz', 'None', 'http://johnkey.co.nz', '1', 'National.png')

Code in the datasource for the formview to get the info

SELECT [ID], [Photo], [Name], [Description], [Joined on] AS Joined_on, [HomeTown], [Affiliation], [Current Location] AS Current_Location, [Gender], [Email address] AS Email_address, [Other accounts] AS Other_accounts, [Personal Website] AS Personal_Website, [Party Logo] AS Party_Logo FROM [FBUser]

I want the Email address and personal website to be clickable

Edit. I need to use ASP to get the code to highlight but I don't know how

I have a view that's bound to a list of models. When using the jquery ui datepicker it'll only change the date on the first model. I'm at a loss.

The model is just the DOB.

js

$(document).ready(function ()
{
    $(function ()
    {
        $(".datepicker").datepicker({ dateFormat: "dd/mm/yy" }).val();
    });
});

View

@model List<tabtest.Models.MyEntity>

    @foreach (var item in Model)
    {
        @Html.TextBoxFor(asd => item.DOB, "{0:dd/MM/yyyy}", new { @class = "datepicker" })
        <br />
    }

Controller

List<MyEntity> myList = new List<MyEntity>();

MyEntity e = new MyEntity();
e.DOB = new DateTime(2014, 5, 25);
myList.Add(e);

e = new MyEntity();
e.DOB = new DateTime(2014, 9, 15);
myList.Add(e);

e = new MyEntity();
e.DOB = new DateTime(2014, 12, 5);
myList.Add(e);

return View(myList);

I'm trying to set up testing with Chutzpah in Visual Studio 2013 and Jasmine tests. I can use fixtures to load in html files, and as far as I understand these will be put inside a default harness file's body.

Instead, I'd like to create tests for the actual production code and basically run some tests on the masterpage we use for all the views to check that everything has loaded correctly, looks the way it should etc.

Is there any obvious way to do this?

I would like to validate my action method parameters using the built validators. However, when I check the ModelState.IsValid the result is always "True"

Take the following snippet that lives inside an ApiController:

public class MyApiController : ApiController
{      
    [HttpGet]
    public string DoStuff([Range(1, 18)] int mustBeBetweenOneAndEighteen)
    {
       if (!ModelState.IsValid) // <-  Always True
       { // ... return error code 
       }
       return null;
    }
}

Apparently this works if you are passing a POCO model and annotate the member variables themselves. Why would this not work also for parameters in the action method itself?