Share tech news, updates, or what's on your mind.

Sign up to Post

I am learning MVC 5. I come from a PHP background, so there is a little learning curve for me.

I want to show a form, do something with the results ( probably email it , but that's not the focus of this question ) - and then on a Thank You page, simply have access to the values of the form submitted.

Here is my skeleton project:

HOME CONTROLLER - partial snippet

        //  Show contact us view
        public ActionResult Contact()
            return View();
       // Show Thank You Page
      // DO I NEED [HttpPost] HERE???
        public ActionResult ThankYou(ContactModel contactData)
           // HOW DO I PASS contactData to my view?
            return View();

Open in new window

ContactModel.cs - I have this file stored in Models/ViewModels folder

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace MyProject.Models.ViewModels
    public class ContactModel
        public string FirstName { get; set; }
        public string LastName { get; set; }

Open in new window

Contact View

<!DOCTYPE html>

<h2>My First MVC Form</h2>

<form action="???????">
  First name:<br>
  <input type="text" name="firstname" >
  Last name:<br>
  <input type="text" name="lastname" ">
  <input type="submit" value="Submit">


Open in new window


<!DOCTYPE html>


<div>Your First Name is: </div>
<div>Your Last Name is: </div>

Open in new window

So that's pretty much where I am.  What do I have to do now to get this thing working?

Also, Where do I put the code to say, email the results? I don't need the code, just where does it go? How do I get access to the form data in my views?

THANKS!! I am excited to see this simple form finally work.

OH, and I know I have to include something like "USING ..." on certain views, but I don't know how.


KuppingerCole Reviews AlgoSec in Executive Report
KuppingerCole Reviews AlgoSec in Executive Report

Leading analyst firm, KuppingerCole reviews AlgoSec's Security Policy Management Solution, and the security challenges faced by companies today in their Executive View report.

var hour = DateTime.Now.Hour;
            ViewBag.WhenToCall = hour < 12 ? "this Morning" : "this Afternoon";

            return View();

This is on a website. How do I adjust the above so it shows = this evening if between 6pm and 11pm in the evening and how can I improve to show certain messages say on a Saturday or Sunday.
Kind regards.
Regular expression validation in mvc class with or .com. I am having my expression as follows
[RegularExpression(@"^\w+([-+.']\w+)*$", ErrorMessage = "Not a valid email")]

Open in new window

I would like to validate with

Open in new window

too like or
.net MVC  or  .net core?

We currently have a web application developed in ASP Classic.
The application is hosted in Microsoft Azure and we use Azure's SQL servers as well as the back-end.

We are still to decide if we move the application and use .net MVC or .net CORE?
I am not too familiar with the pros vs cons.  If there is a website with more information on comparing the two would be great.

I also understand CORE is newer and may not be as mature, do you consider this to be a significant problem?  Moving the system will take about 1 year.
we are using a Bootstrap 'template', AJAX, JSON, XML, etc.

Another thing to consider is that I downloaded Visual Studio in my mac. It would be great if I could check the code there and test the system in the mac computer.
I guess the challenge there will be to connect to our Development Database in Azure.

Any help, guidance, tips and especially comparison would be very useful. I know that sometimes its a matter of taste and seeing both sides of the argument would be very beneficial.
Good morning,

Could you please suggest me about the libraries/Nuget packages that can be used to read data from word doc or PDF file.

It would be great help, if you could provide a piece of code using MVC 5.

exception in chrome
button source code
I am getting an exception
Uncaught Error: cannot call methods on button prior to initialization; attempted to call method 'loading'

when I click a button more than 5 times after that the button stops working
I am having a devil of a time working out jqgrid using subgrid as a grid for my grid view in MVC. I can get the grid working with out an issue but I seem to be having issues with the json call to get the subgrid to populate. Please let me know if I am doing something incorrectly or if you have any suggestions on improving the code.


        url: "/List/GetItems",
        datatype: 'json',
        mtype: 'Get',
        colNames: ['ID', 'Item'],
        colModel: [
            { key: true, hidden: true, name: 'ID', index: 'ItemID' },
            { key: false, name: 'Item', index: 'Item', editable: true }
        pager: jQuery('#jqControls'),
        rowNum: 20,
        rowList: [10, 20, 30, 40],
        height: '100%',
        viewrecords: true,
        multiselect: false,
        caption: 'Item Records',
        emptyrecords: 'No Records are Available to Display',
        jsonReader: {
            root: "rows",
            page: "page",
            total: "total",
            records: "records",
            repeatitems: false,
            Id: '0',
        autowidth: true,
        multiselect: false,
        subGrid: true,
        subGridRowExpanded: function (subgrid_id, row_id) {
            var sg_tableID = subgrid_id + "_t";
            jQuery("#" + subgrid_id).html("<table id='" + sg_tableID + "' class'scroll'></table>");
            jQuery("#" + sg_tableID).jqGrid({
                url: "/List/getTaskSubList" + 

Open in new window

I am trying to populate a ViewModel and I am getting an "Object reference not set to an instance of an object." when trying to populate a List within my main view model. See my two ViewModels and my code to populate them.

As you can see I am building a List of InventoryWorkTypesMSViewModel from a common delimited field of WorkTypes in the InventoryViewModel. Am I doing this wrong? If so what should I do to fix it?

public class InventoryViewModel
        public int InventoryId { get; set; }
        public int ProjectId { get; set; }
        public int Qty { get; set; }
        public bool AuditFlag { get; set; }
        public string UpdatedBy { get; set; }
        public DateTime? UpdatedDt { get; set; }
        public int? ProductNameId { get; set; }
        public string Size { get; set; }
        public string WorkTypes { get; set; }
        public List<InventoryWorkTypesMSViewModel> WorkTypesMS { get; set; }

public class InventoryWorkTypesMSViewModel
        public string WorkType { get; set; }

public List<InventoryViewModel> GetList(int projectId, int? productNameId)
                var model = _db.Inventories
                        .Select(i =>
                              new InventoryViewModel
                                  InventoryId = i.InventoryId,
                                  ProjectId = i.ProjectId,
                                  Qty = i.Qty,

Open in new window

I want to show DropDown list of Availabe .resx files from Resources folder on viewpage inorder to display selected .resx contents. I displayed the contents but how can i show dropdown of the available .resx files ???
Free Tool: Port Scanner
LVL 12
Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

I'm trying to run a bat file (with parameters) from an MVC controller.  Can somebody please tell me what I'm doing wrong?  When I run this without parameters it works.  When I add parameters, it doesn't.  I get no errors.

This is what it should look like at the command line:
cd C:\Program Files (x86)\Microsoft Visual Studio 12.0\Common7\IDE\CommonExtensions\Microsoft\TestWindow
vstest.console.exe "c:\Program Files (x86)\myFolder\SeleniumTest.dll" /TestCaseFilter:"TestCategory=Main Menus"

Open in new window

code snippet from Controller:
steName = Name; //parameter

            Process myProcess = new Process();

                myProcess.StartInfo.UseShellExecute = false;
                myProcess.StartInfo.WorkingDirectory = @"C:\scripts";
                myProcess.StartInfo.FileName = @"C:\scripts\CmdRunTests.bat";
myProcess.StartInfo.Arguments = steName;
//myProcess.StartInfo.Arguments = String.Format("\"{0}\"", steName); //Also tried this line

bat file:
set steName=%1
@echo off
cd C:\Program Files (x86)\Microsoft Visual Studio 12.0\Common7\IDE\CommonExtensions\Microsoft\TestWindow
vstest.console.exe "c:\Program Files (x86)\myFolder\SeleniumTest.dll" /TestCaseFilter:"TestCategory=%1"

Open in new window

Hello... new to linq lambda - what is wrong with my query? - I get 'sequence contains no elements' error when there are no providerSpecialties records for the given provider.

This should behave like a left join from the provider entity.

             return DBContext.Provider.GroupJoin(DBContext.ProviderSpecialties,
                    p => p.providerId, ps => ps.providerSpecialtyId, (p, ps) => new { Provider = p, ProviderSpecialties = ps.DefaultIfEmpty()})
                    .SelectMany(a => a.ProviderSpecialties
                    .Select(b => new { Provider = a.Provider, ProviderSpecialties = b }))
                    .Where(w => w.ProviderSpecialties.isPrimary == true)
                    .Where (w => w.Provider.providerId == providerId)
                    .Select(m => new ProviderDetail
                        providerId = m.Provider.providerId,
                        NPI = m.Provider.NPI,
                        licenseNumber = m.Provider.licenseNumber,
                        licenseExpiration = m.Provider.licenseExpiration,
                        licenseStateId = m.Provider.licenseState,
                        licenseStateName = m.Provider.State.abbreviation,
                        networkLevelId = m.Provider.networkLevel,
                        networkLevelName =,
                        firstName = m.Provider.firstName,
                        lastName = m.Provider.lastName,

Open in new window

I am very new to mvc and ajax, any help would be very welcome!

I am trying to call a stored procedure by Ajax call. I am passing a model and am very confused how i am getting 1 value passed correctly but my timedate values seem to be dropped.


    <input type="hidden" name="Id" value="1" id="Id" />
     Date:  <input type="text" id="Status_Date" class="datePicker" />
     Time: <input type="text" id="Status_Time" class="timePicker" />
    <button type="submit" value="Submit" class="save-bdm">SubmitMe</button>


Open in new window

 ajax call
<script type="text/javascript">
        $(function () {
            $('.save-bdm').on('click', function () {
                var tr = $(this).parents('tr:first');
                var Id = tr.find("#Id").val();
                var Status_Date = tr.find("#Status_Date").val();
                var Status_Time = tr.find("#Status_Time").val();
                var CallSPUpdateModel =
                        "Id": Id,
                        "Status_Date": Status_Date,
                        "Status_Time": Status_Time
                    url: '/SPCall/CallSP/',
                    data: JSON.stringify(CallSPUpdateModel),
                    type: 'POST',
                    contentType: 'application/json; charset=utf-8',
                    success: function (data) {
                    error: function (jqxhr, textStatus, errorThrown) {
                        alert('Exception ' + + ' Error: ' + errorThrown + ' status ' + textStatus);


Open in new window

Controller: I did commit out my to DB so i dont jsut run the SP over and over again. I am checking my return with the message to see if the values are passed correctly.

public JsonResult CallSP(CallSPUpdateModel model)

            SqlConnection con = new SqlConnection(connectionString);
            SqlCommand cmd = new SqlCommand();
            cmd.Connection = con;
            cmd.CommandType = System.Data.CommandType.StoredProcedure;
            cmd.CommandText = "Update_SP";
            cmd.Parameters.Add(new SqlParameter("@Id", "1"));
            cmd.Parameters.Add(new SqlParameter("@myDate", "01/08/2018"));
            cmd.Parameters.Add(new SqlParameter("@myTime", "16:00:00"));
            //object o = cmd.ExecuteScalar();

            string message = "Success from Controler " + model.Id + " : " + model.Status_Date + " : " + model.Status_Time;
            return Json(message, JsonRequestBehavior.AllowGet);

Open in new window

Thank you for taking a look at this and any direction you can give. Im sure its a simple mistake but im just not seeing it.
I am using KendoUI for textbox and want to convert the keyed letters to uppercase. Below is the code I use for textbox

@html.Kendo().TextboxFor(model => model.t1).HtmlAttributes(new {maxlength=55})

also tried @html.Kendo().TextboxFor(model => model.t1).HtmlAttributes(new {maxlength=55, style = "text-transform:uppercase"})
 but didnt work

Please help.
I have a MVC 5 project and a few older ASPX pages i would like to link from an MVC page. Is there any way to add the ASPX files to the existing MVC project? Can I just put all the files from both MVC and the aspx files on iis and just call the aspx page from a html link?

Thank you for any help you can give
Hello, I am pretty new to mvc sites and trying to figure out the jQuery date picker in a web grid. I am able to put the date picker into my layout so it renders to all pages:

 <link href="~/Content/themes/base/jquery-ui.min.css" rel="stylesheet" />
    <script src="~/Scripts/jquery-2.2.4.min.js"></script>
    <script src="~/Scripts/jquery-ui-1.12.1.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function () {
                dateFormat: "dd-mm-yyyy"


Open in new window

and can add the class to my webgrid, and it does display but I do not get an date value entered into the field when i select a date from the calendar:

webGrid.Column("Calendar_Dt", "Calendar Date", format: @<text>  <span class="display-mode"> <label id="lblCalendar_Dt">@item.Calendar_Dt</label> </span> <input type="text" id="Calendar_Dt"  class="edit-mode datePicker" /></text>, style: "col2Width")

Open in new window

What I am doing incorrectly here?

Thank you for any help you can provide.

It seems that the datepicker does not like the names of the input being the same and that is why if you update row 5 the value is placed in the row 1 textbox.  Is there a way to refer back to the webgrid row by index value or some other unique name such as name=""?
Hi Experts,
I am using a Kendo UI grid in my MVC.Net application.
I have added an onclick event to one of my grid's columns.  The event takes 1 parameter (the value of the BatchID columns).
I also want to pass the value of the FileName column a second parameter.  Is this possible to do using the template of a given column?
If so, how?

You can see my code, and an image of my code below:
    function loadLog() {
        var BatchID = $("#hdnBatchID").val();
            dataSource: {
                type: "ajax",
                transport: {
                    read: function (options) {
                            type: "POST",
                            url: '@Url.Action("GetLog", "EDI")',
                            dataType: "json",
                            data: JSON.stringify({ "BatchID": BatchID}),
                            contentType: 'application/json; charset=utf-8',
                            success: function (result) {
                                var data = result.FileDtls;
                                if (data != null)
                schema: {
                    data: function (response) {
                        return response.FileDtls;

Open in new window

I need to remove a dangerous domain from the URL, but the QueryString Collection is Read Only.
I created a whitelist of safe URL's and scan the URL inside a custom ActionFilterAttribute to assert that every domain is whitelisted:

But rather than upsetting existing program flow by redirecting to an error page, we have decided to simply remove that dangerous domain. If the goto or returnURL is errant, I need to completely remove it. But, the QueryString Collection is Read Only.

I use the following code to remove the "goto" key and notice the NameValueCollection array drops from a size of 1 to 0.

        private void RemoveParameter(NameValueCollection nameCollection, string keyToRemove)
            // reflect to readonly property
            PropertyInfo isreadonly = typeof(System.Collections.Specialized.NameValueCollection).GetProperty("IsReadOnly", BindingFlags.Instance | BindingFlags.NonPublic);

            if (isreadonly != null)
                // make collection editable
                isreadonly.SetValue(nameCollection, false, null);

                // remove

                // make collection readonly again
                isreadonly.SetValue(nameCollection, true, null);

Open in new window

but even after a final call to:


the browser still has the bad domain in the goto. In fact, I was expecting "goto" to no longer display.

What am I missing?

RedirectResult from ActionFilterAttribute

I made a custom ActionFilterAttribute which checks a URL to see if the domains are contained in a whitelist of domains. It's working, but I need to redirect to a failure page on failure.

Can I use the following call?

filterContext.Result = new RedirectResult("/error/Unauthorized");

and what about the path?

I see

ErrorController : Controller
with the following action method

public ActionResult Unauthorized

and it returns the following view:

            return View("UserNoPermissions");

and I see the Shared View


yet, I get the error:

HTTP Error 404.0 - Not Found
The resource you are looking for has been removed, had its name changed, or is temporarily unavailable.

Get Cisco Certified in IT Security
Get Cisco Certified in IT Security

There’s a high demand for IT security experts and network administrators who can safeguard the data that individuals, corporations, and governments rely on every day. Pursue your B.S. in Network Operations and Security and gain the credentials you need for this high-growth field.

C#: Can AuthorizeAttribute.GetRedirectResult() be hacked?

I see the following over-ride of GetRedirectResult()

        private ActionResult GetRedirectResult(AuthorizationContext context, string controller, string action, string clientId = null,
            List<KeyValuePair<string, object>> additionalParameters = null)
            var returnUrl = context.HttpContext.Request.RawUrl;


Open in new window

but notice the value for Request.RawUrl is a simple path, generated by our code:


So, I wonder if I need to do any URL sanitizing on this, given it seems based on C# and not user generated.

Is this something that can be ignored?

I am having a bit of a problem in my ajax call, I am getting 2 of my 3 values passed and everything works if i hard code my 3rd value for the db updates but for the life of me i am not seeing why 1 value is not being passed from the view to the controller. I am sure i am just not seeing a mistake i am making.

From the below the only value not being passed correctly is inc which is a number. I know that I am missing that number due to the return json message showing a 0 for that value and if i hard code the value in my sql the update works for the other 2 values.

from view:
    var webGrid = new WebGrid(Model);

        htmlAttributes: new { @id = "WebGrid", @class = "Grid" },
        columns: webGrid.Columns(
        webGrid.Column("Inc", format: @<text>  <span class="display-mode">@item.Inc</span> <label id="Inc" class="edit-mode">@item.Inc</label> </text>, style: "col1Width"),
        webGrid.Column("Include", "Include", format: @<text>  <span class="display-mode"> <label id="lblInclude">@item.Include</label> </span> <input type="text" id="Include" value="@item.Include" class="edit-mode" /></text>, style: "col2Width"),
        webGrid.Column("Desc", "Description", format: @<text>  <span class="display-mode"> <label id="lblDesc">@item.Desc</label> </span> <input type="text" id="Desc" value="@item.Desc" class="edit-mode" /></text>, style: "col2Width"),
        webGrid.Column("Action", format: @<text>
            <button class="edit-inc 

Open in new window

Hi, I'm using Visual Studio 2017.  I created a C# Web API with MVC checked project.  It comes  with a basic structure already.  It has the HomeController and the ValuesController cdoe in the project explorer.  Build and ran the problem and it lands and shows the Home's Index view page no problem.  However, I get error when I accessed the ValuesController Get API.  Please see the attached image.  With this message and my break point, it does reach and execute the Get() API no problem by me adding /api/Values
But then the browser would ask if I want to save or open, if I select open then I got the error.  It's having problem opening and displaying the values.json file.  

The ValuesController.Get() api doesn't return a ActionResult so I assume it doesn't need a View created and the context menu doesn't show adding view is an option to it.  Is this correct?

  I looked up the error online and it seems it'a registry corruption issue.  I'm running Visual Studio 2017 Enterprise installer again in Repair mode.  I'm hoping that would fix it or I would have to mess with the registry values.

I'm also attaching the screen cap pop up text at the bottom of the screen when I call the Get or Get id api.

Thank you
Need to find where query params are added to a .NET Solution.

I need to search through multiple solutions and find the many places where query string params are added to the URL. So, I wonder about all the ways this can be done.

Have you got any searches I can do that would help me track those down?

My fear is that finding them all would be nearly impossible, given you can insert a query parameter just be concatenating a string.

But, please make suggestions about explicit commands and objects used, and other more general keywords I can search for, to discover where URL's are being created.

Hey all,

I am working on redesigning our main CRM for a rewrite.  We are primarily a .NET shop so I am thinking MVC for the front end, but I am trying to figure out the best design approach for the middle tier (business logic).  I am pretty sure I want to expose the data layer via a restful API, so WebAPI on .NET CORE seems to be a good fit.  

In my research, I had a couple question.
  1. As I delve more and more into MVC, it seems that could just as easily return an "object" from a controller as I could a view.  If that is the case, is there any reason not to just include my API logic in the MVC application instead of making a separate project?
  2. I have learned that I can use scaffolding to generate classes automatically from the database, is there a way to automatically generate controllers for my classes?
  3. (I know this one is pretty general) Are there other/better technologies I should be looking at?

Thanks in advance.
I have an MVC form which a user can arrive at from two entirely different controllers/views - I have a cancel button on the form that I would like to simply navigate the user back to their previous page, whichever one they came from.

The button is a straight HTML anchor, not an actionlink:
<a class="btn btn-primary cancelNav" href="">Cancel</a>

Open in new window

On the client-side, I am using unobtrusive jQuery to attach an anonymous function to the link:
    $(document).on('click', '.cancelNav', function () {

Open in new window

I have experimented with numerous approaches here, using window.location, window.history and have verified that the correct URL with params is being passed, but all result in:
"System.ArgumentException: The parameters dictionary contains a null entry for parameter 'id' of non-nullable type 'System.Int32' for method 'System.Web.Mvc.ActionResult Edit(Int32)'"
yet I can click the browser's back button with no issue.

Can someone tell me why?






Top Experts In