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>
<html>
<body>

<h2>My First MVC Form</h2>

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

</body>
</html>

Open in new window


THANK YOU View

<!DOCTYPE html>
<html>
<body>

<h2>Thanks!</h2>

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

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.

Regards,

John
0
Cloud Class® Course: Microsoft Exchange Server
LVL 12
Cloud Class® Course: Microsoft Exchange Server

The MCTS: Microsoft Exchange Server 2010 certification validates your skills in supporting the maintenance and administration of the Exchange servers in an enterprise environment. Learn everything you need to know with this course.

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.
0
Regular expression validation in mvc class with co.in or .com. I am having my expression as follows
[RegularExpression(@"^\w+([-+.']\w+)*@company-usa.com$", ErrorMessage = "Not a valid email")]

Open in new window

I would like to validate with
@company.in

Open in new window

too like user@company-usa.com or user@company.in
0
I have mvc project with one layout cshtml with some js codes. My goal is to take the parameter (viewbag) value to js file on layout.cshtml.
I try the codes below and "test" does not shown any value when I open the browser >> view source

Do you know how to fix it?

Thanks,


layout.cshtml
<script>

  var test = @ViewBag.showMe
  var locations =
                    [
                 test
                     [locationData('listings-single-page.html', 'http://localhost:29792/images/listing-item-01.jpg', "Tom's Restaurant", '964 School Street, New York', '3.5', '12'), 40.94401669296697, -74.16938781738281, 1, '<i class="im im-icon-Chef-Hat"></i>'],
                     [locationData('listings-single-page.html', 'http://localhost:29792/images/listing-item-02.jpg', 'Sticky Band', 'Bishop Avenue, New York', '5.0', '23'), 40.77055783505125, -74.26002502441406, 2, '<i class="im im-icon-Electric-Guitar"></i>'],
                     [locationData('listings-single-page.html', 'http://localhost:29792/images/listing-item-03.jpg', 'Hotel Govendor', '778 Country Street, New York', '2.0', '17'), 40.7427837, -73.11445617675781, 3, '<i class="im im-icon-Home-2"></i>'],
                     ];  
</script>


Home
Controller:
  public ActionResult Index()
        {
             ViewBag.showMe = " [locationData('listings-single-page.html', 'http://localhost:29792/images/listing-item-01.jpg', "Tom's Restaurant", '964 School Street, New York', '3.5', '12'), 40.94401669296697, …
0
We have an MVC app with a significant amount of javascript code.  We have found a number of our users' browsers are not refreshing Javascript files when they change and are updated on our IIS server.  We have needed to CTRL+R to force a refresh on these browsers.  

How can we address this?
0
In one of the module of our project there are multiple related objects. Here are few of them and the relationships
  • Project
  • Discussions (Related to project. A project must have at least one discussion, 1-M relation)
  • Surveys (Each discussion can have multiple Surveys. Surveys can be added later on, 0-M relation)
  • Questions (Surveys can have questions One survey must have at least one question, 1-M relation)
  • Expected Attendees (A project can have expected attendees, 0-M relation)
There are some other objects as well related to this scenario which I did not included here. In the time of creating a new project entire data needs to be saved in one go. Later on user may add other elements (discussion, surveys etc.) in an existing record.

In Data layer and business layer I created classes for each and every objects (Project, Discussion, Surveys, Question and Attendee). Since in the time of creating a new project few of actions (Survay save, Expected Attendee save etc.) are optional so we are thinking of Decorator pattern to save a project.

Now I have two questions

Should we implement decorator pattern? Or is there any other pattern which address this situation better?
We have to implement the patter in business logic layer. In that case how can I implement transaction? This is a key problem when we are trying to implement any design pattern.
0
.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.
0
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.

Thanks
0
I have mvc app that using bundle to generate CDN. Everything in localhost / development environment is working fine.
But when I publish to azure environment and debug using firewall. it alerts all CDN is missing.

Can you tech me what I need to do to avoid this issue occurred...?

Thanks

public class BundleConfig
    {
        // For more information on bundling, visit http://go.microsoft.com/fwlink/?LinkId=301862
        public static void RegisterBundles(BundleCollection bundles)
        {
            bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
                        "~/Scripts/jquery-{version}.js"));

            //bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
            //            "~/Scripts/jquery.validate*"));

            // Use the development version of Modernizr to develop with and learn from. Then, when you're
            // ready for production, use the build tool at http://modernizr.com to pick only the tests you need.
            bundles.Add(new ScriptBundle("~/bundles/modernizr").Include(
                        "~/Scripts/modernizr-*"));

            bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include(
                      "~/Scripts/bootstrap.js",
                      "~/Scripts/respond.js"));

            bundles.Add(new StyleBundle("~/Content/css").Include(
                      //"~/Content/bootstrap.css",
                      "~/Content/site.css"));
        }
    }

Open in new window

0
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
0
Network Scalability - Handle Complex Environments
Network Scalability - Handle Complex Environments

Monitor your entire network from a single platform. Free 30 Day Trial Now!

Below codes working but for some reasons it supposes to return 6 records from the ms sql database.but it ends up return 1 record only.
Can you help me to fix it?

Thanks
public ActionResult Index()
        {
return View(EventFleetList());
}
public List<Domain.Fleet> EventFleetList()
        {
            Domain.Fleet f = new Domain.Fleet();
            List<Domain.Fleet> fleetList = null;
            using (SqlConnection connection = new SqlConnection(connectionString))
            using (SqlCommand command = new SqlCommand("",connection))
            {
                connection.Open();
                command.CommandText = "SELECT * FROM Fleet";
                SqlDataReader reader = command.ExecuteReader();
                if (reader.HasRows)
                {
                    while (reader.Read())
                    {
                        string id= reader["FleetID"].ToString();
                        fleetList = new List<Domain.Fleet>()
                        {
                                new Domain.Fleet
                                {
                                    id =1,
                                    make = id + " Make",
                                    model = id + " Model"
                                },                                
                        };
                    }
                }
             }
            return fleetList;
        }             



//mvc razor
@model List<Domain.Fleet>  

Open in new window

0
We have a cloud web application developed in .net MVC c#.now I'm starting​ integrate with sage 50 desktop application. Sage 50 provide an SDK for integration. We have to pass data like create invoice,from my web application. So how to do this process? Which is the best solution? Which technology we use here? Web service and things are recommend from sage support team.but how to use this?

Please advise for this,access desktop application from web.
0
I have added areas to my asp.net MVC application, and I have created models inside the area I have created, I'm trying to add the model to the public class ApplicationDbContext : IdentityDbContext<ApplicationUser>, so I can create a migration and update database to get that table added to my DB. but its not recognized. which is the right way of adding models that are located in areas to have them created in the database?
Thanks

PS Im using the code first approach.
0
I am developing a C# .net MVC page to allow users to make some selection, query data and display the data with paging function.
I use a partial view for the data display but fail to maintain the main view and the data after click on different page.

Please advise me, have attached the code as below (Index.cshtml, SearchController.cs, WebGrids.cshtml)

Index.cshtml
______________

@model DLTWeb.Models.SearchModel

@{
    ViewBag.Title = "Index";    
}

<header>
    <script src="~/Scripts/jquery-3.0.0.js"></script>
    <script src="~/Scripts/jquery-3.0.0.min.js"></script>
    <script src="~/Scripts/jquery-ui-1.8.24.min.js"></script>  
    <script src="~/Scripts/gridmvc.min.js"> </script>
    <link href="@Url.Content("~/Content/style.css")" rel="stylesheet" type="text/css" />  
    <link href="@Url.Content("~/Content/PagedList.css")" rel="stylesheet" type="text/css" />
</header>

<h2><font color="blue">@Html.Label("lblReport", "DLT Web Report")</font></h2>

<br />

<table>
    <tr>
        <td>Report Name</td>
        <td>@Html.DropDownListFor(m => m.ReportName, (IEnumerable<SelectListItem>)ViewBag.ListReport, "---------------Select Report----------------", new { @id = "ddlReport", @onchange = "javascript:GetFields(this.value);" })</td>        
    </tr>
    <tr>
        <td>Fields Name</td>
        <td>
            <select id="ddlFields" name="ddlFields">
                <option>---Select Fields---</option>
            </select>
        …
0
I have new using mvc, and I have the following sql statement that will loop for 40 records.
how to make the codes reflect on razor?

    public ActionResult Index()
        {
            Domain.Fleet f= new Domain.Fleet
            {
                //SELECT COUNT(FleetInEvent.FleetID)AS totalCountFleet, WebsiteSetting.EventName FROM FleetInEvent INNER JOIN
                //WebsiteSetting ON FleetInEvent.Domain = WebsiteSetting.Domain GROUP BY WebsiteSetting.EventName ORDER BY WebsiteSetting.EventName
                id = 1,
                totalFleetCount = 200
            };
            return View(f);
        }
0
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.


JS:

$("#jqGrid").jqGrid({
        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

0
I have been developing with ASP.NET web forms for years and had decided to learn MVC and Entity Framework model as I am becoming irrelevant in skill set. But in discussions with some of my peers they indicated I should start with ASP.NET Core Razor environment. Since I have had limited exposure to both, I need suggestions on where to get started, kind of like a step one learn this, step two learn that. I am kind of at a loss of where to begin as it all looks so foreign to what I am used to.
0
I have the codes below
1. RetrieveData is working fine., but now I want to assign class library value in a loop.
Basically, I have wcf call to get the list of name which is exactly same as class library property name - see newretrievedata
Is it possible to do that?

On another side of class library in c#, i already have all of the property/object in class library.


     
  public JsonResult RetrieveData(string ID)
        {
            Domain.Lead l = new Domain.Lead();
            l.firstname = "John";
            l.lastname = "Smith";
            return Json(l, JsonRequestBehavior.AllowGet);
        }

 
        public JsonResult newRetrieveData(string ID)
        {
            Domain.Lead l = new Domain.Lead();


            foreach (KeyValuePair<string, string> i in Helper.DynamicsCRM.GetAllLeadInfoByMetaData3("a51ec467-7255-e811-81153863bb3c4538"))
            {               
                //Response.Write(i.Key + " >> " + i.Value + "<br>"); Key has firstname, and lastname, etc.
            	l.i.Key = i.Value;
            }
            return Json(l, JsonRequestBehavior.AllowGet);
        }

Open in new window

0
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

0
Problems using Powershell and Active Directory?
LVL 8
Problems using Powershell and Active Directory?

Managing Active Directory does not always have to be complicated.  If you are spending more time trying instead of doing, then it's time to look at something else. For nearly 20 years, AD admins around the world have used one tool for day-to-day AD management: Hyena. Discover why

I am currently experiencing something strange with one of my routes' responses and haven't been able to find any information elsewhere.

So, let's say I make a call to a route in my controller with JQuery, like this. It's a POST action and I expect JSON data.

// Send the data
            $.ajax({
                type: "POST",
                enctype: 'multipart/form-data', //'application/json',  
                url: "/Claims/Application/SaveCurrentFormData",
                data: data,
                dataType: 'json', // we're expecting back a json
                processData: false,
                contentType: 'application/json',
                cache: false,
                timeout: 600000,
                success: function (result) {                      
                    for (var formCode in result.forms) {
                        var selector = "[data-formcode='" + formCode + "']";
                        $(selector + " [name='TicketDocumentId']").val(result.forms[formCode]);
                    }

                    for (var documentName in result.documents) {
                        var selector = "input[name='" + documentName + "']";
                        $(selector).data("ticketdocumentid", result.documents[documentName]);
                    }

                    resolve(true);
                },
                error: function (e) {
                    // Debug
                    console.log("Error saving form data: ", e.message, e);

        

Open in new window

0
Hello to all I tried an enterprise structure like below:

image

And my models are like so:

public class Course : Entities
    {
      
        public int Credits { get; set; }
 
        public virtual ICollection<Enrollment> Enrollments { get; set; }
      
    }
 
  public enum Grade
    {
        A, B, C, D, F
    }
    public class Enrollment : Entities
    {
      
 
        public int CourseID { get; set; }
        public int StudentID { get; set; }
        public Grade? Grade { get; set; }
 
        [ForeignKey("CourseID")]
        public virtual Course Course { get; set; }
        [ForeignKey("StudentID")]
        public virtual Student Student { get; set; }
        
    }
 
 public class Student: Entities
    {
       
        public string LastName { get; set; }
        public string FirstMidName { get; set; }
        public DateTime EnrollmentDate { get; set; }
 
        public virtual ICollection<Enrollment> Enrollments { get; set; }
        
    }
 
  public class Entities:IEntity
    {
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        [Key]
        public int ID { get; set; }
        [Required]
        public string Title { get; set; }
    }
 
 public interface IEntity
    {
          int ID { get; set; }
        //string Title { get; set; }
    }

Open in new window


And my context:

 public EFBlogContext()
            : base("Blogst")
        {
        }
        public DbSet<Student> Students { get; set; }
        public DbSet<Enrollment> Enrollments { get; set; }
        public DbSet<Course> Courses { get; set; }
 
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
         
            
            base.OnModelCreating(modelBuilder);
        }

Open in new window


And here is my up method:


Open in new window

0
Below code is working in web form. But I convert into mvc so I have <select id="htmlList"></select>
so how can i use Helper.DynamicsCRM.GetOptionSetItems("lead", "new_rv_type") binding with "htmlList"?


Web Form
ddlTitle.DataSource = Helper.DynamicsCRM.GetOptionSetItems("lead", "new_rv_type");
ddlTitle.DataBind();
<asp:DropDownList runat="server" ID="ddlTitle" DataTextField="text" DataValueField="value"></asp:DropDownList>
0
i JUST WANT TO know how to consume below api by using c# code behind

https://apidocs.leadsquared.com/create-a-lead/
0
try to publish from mvc app to azure.
even I remove all of the files and folder in obj folder,
this issue still bothering us for each website. It is not codes issue because even we tried to publish empty website. the issue remain  the same.


Copying file bin\System.Web.Mvc.xml to obj\Release\Package\PackageTmp\bin\System.Web.Mvc.xml failed. Could not find file 'bin\System.Web.Mvc.xml'.
0
I have the html form below in index.cshtml
and want to submit them to email using code behind.
I am new on MVC, and can you show me how to do that? I know how to send email in codes, just do not want what is the best practice to carry the data into code behind.

<form class="account-settings-form" id="form">
                        <br /><br />
                        <h5>General Information</h5>
                        <p class="small-paragraph-spacing">By letting us know your name, we can make our support experience much more personal.</p>
                        <div class="row">
                            <div class="col-sm">
                                <div class="form-group">
                                    <label for="first-name" class="col-form-label">First Name:</label>
                                    <input type="text" required class="form-control" id="first-name" placeholder="Your First Name">
                                </div>
                            </div><!-- close .col -->
                            <div class="col-sm">
                                <div class="form-group">
                                    <label for="last-name" class="col-form-label">Last Name:</label>
                                    <input type="text" required class="form-control" id="last-name" placeholder="Your Last Name">
                                </div>
                            </div><!-- close .col -->
                            <div 

Open in new window

0

.NET MVCSponsored by Jamf Now

177

Solutions

194

Contributors

Top Experts In
.NET MVC
<
Monthly
>