Category Archives: Label

Label

[RESOLVED]AngularJS in ASP.NET MVC Partial View

I am currently loading Partial View returned by MVC controller to a model dialog via AngularJS $http.get call. My View in rendered properly in modal dialog, but the only problem is that my partial view which is rendered also uses angular expressions etc.
and for some reason angular is not working in my partial view, but if i load this partial view in some other view without ajax call then it angular works properly.

Partial View Code: ~/Views/ArticleType/_Add
MVC Controller: ArticleTypeController

//other scripts files e.g app.js and angular.js are included in main layout file.
<script src="~/Scripts/Angular/ArticleTypeController.js"></script>
<div class="modal-content" ng-controller="ArticleTypeController">
    <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
        Add New Article Type
    </div>
    <form novalidate role="form" name="ArticleTypeForm" ng-submit="ArticleTypeForm.$valid && Add(model)">
        <div class="modal-body">
            <div class="form-group">
                <label for="ArticleType" class="control-label">Article Type</label>
                <input type="text" required ng-model="model.ArticleTypeName" class="form-control" id="ArticleType" />
            </div>
        </div>
 
    </form>
    <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
        <button type="submit" class="btn btn-primary" value="Add" >Add</button>
        {{ArticleTypeForm.$valid}}
    </div>
</div>

Angular Controller to load modal with the partial view.
MenuController.js

angular.module('myApp').controller('MenuController', [
        '$scope', '$http', 'httpPreConfig', function ($scope, $http, httpPreConfig) {
 
            $scope.AddArticleType = function () {
                $.get("/ArticleType/Add")//returns the partial view.
                    .success(function (response) {
                        ShowModal(response);//it properly shows the modal. but angular doesn't work
                    });
            }
        }]);

common.js 

$(document).ready(function (e) {
    
    $(document).ajaxStart(function (e) {
        $("#loadingBar").modal('show');
    });
    $(document).ajaxStop(function(e) {
        $("#loadingBar").modal('hide');
    });
    $(document).ajaxComplete(function (e) {
        $("#loadingBar").modal('hide');
    });
    $(document).ajaxError(function (e) {
        $("#loadingBar").modal('hide');
    });
});
 
function ShowModal(content) {
 
    //var html = $complie(content)(scope);
    $("#modal .modal-dialog").html(content);
    $("#modal").modal("show");
}
function HideModal() {
    $("#modal .modal-dialog").html("");
    $("#modal").modal("hide");
}

AS you can see from the image below that Angular expressions are not working in Modal Dialog. The html of this dialog is returned from MVC Controller whcih returns a partial view. 

Any help would be really appreciated. Just so that you know, angular expressions etc. are working in normal views.

Here is the download link to the solution files. : https://app.box.com/s/rxvrhwcdp75zo736k7u5

Hi asad,

According to your description, it works fine if you load that partial view directly, however it doesn’t work if using the AJAX to load the partial view.

I think you may need to compile HTML string or DOM into a template.

More information, please refer to:

# $compile

https://docs.angularjs.org/api/ng/service/$compile  

There are some threads that may help you:

# AngularJS – Dynamically creating elements that specify directives

http://stackoverflow.com/questions/20025526/angularjs-dynamically-creating-elements-that-specify-directives

# Bind Angularjs to newly created html element dynamically

http://stackoverflow.com/questions/19867554/bind-angularjs-to-newly-created-html-element-dynamically

Best Regards

Starain Chen

[RESOLVED]Need help to create Cascading DropDownList using MVC4 – C# from Database

I have 2 dropdown lists  (State and City) in my form and I want to show them as Cascading DropDownList.

When I select a State then I want to display only the related cities in that state.

My mode:

public class AustraliaStates
    {
        [Key]
        public string AustraliaStateId { get; set; }
        public string AustraliaStateName { get; set; }
    }

    public class AustraliaCities
    {
        [Key]
        public string AustraliaCityId { get; set; }
        public string AustraliaCityName { get; set; }
    }



    public class Accommodation
    {
        [Key]
        public string A_Unique_Id { get; set; }

        [Display(Name = "Street")]
        public string Street { get; set; }

        [Required]
        [Display(Name = "Suburb")]
        public string Suburb { get; set; }

        [Display(Name = "City")]
        public string City { get; set; }

        [Display(Name = "State")]
        public string State { get; set; }

        public string SelectedAustraliaStateId { get; set; }
        public IEnumerable<SelectListItem> AustraliaStates { get; set; }


        public string SelectedAustraliaCityId { get; set; }
        public IEnumerable<SelectListItem> AustraliaCities { get; set; }
    }

Create.cshtml Get controller:

// GET: /Accommodation/Create
        [Authorize]
        public ActionResult Create()
        {

            var model = new Accommodation
            {
                AustraliaStates = db.AustraliaStates
                             .ToList() // this will fire a query, basically SELECT * FROM Products
                             .Select(x => new SelectListItem
                             {
                                 Text = x.AustraliaStateName,
                                 Value = x.AustraliaStateId
                             }),

                AustraliaCities = db.AustraliaCities
                             .ToList() // this will fire a query, basically SELECT * FROM Products
                             .Select(x => new SelectListItem
                             {
                                 Text = x.AustraliaCityName,
                                 Value = x.AustraliaCityId
                             });
                


            return View(model);
        }

Create.cshtml View

<td class="FormDisplayRightTableStyle">
                                <div class="editor-field">
                                    @Html.DropDownListFor(model => model.SelectedAustraliaStateId, Model.AustraliaStates, new {@class="DropDownFieldStyle" })

                                </div>
                            </td>    
                        </tr>

                        <tr>
                            <td class="FormDisplayLeftTableStyle">
                                <div class="editor-label">
                                    @Html.LabelFor(model => model.City)
                                </div>
                            </td>
                            <td class="FormDisplayRightTableStyle">
                                <div class="editor-field">
                                    : @Html.DropDownListFor(model => model.SelectedAustraliaCityId, Model.AustraliaCities, new {@class="DropDownFieldStyle" })
                                </div>
                            </td>    
                        </tr>

I need to solution to show the DDL as Cascading DropDownList.

can someone please help me?

Thanks in advance.

Here is the form I am working on:

http://overseasindians.com.au/Accommodation/Create

Typical cascading dropdown lists only load the first list initially.  So in your case, you would load your States to the view.  Upon selecting a state, a JSON get-request is made back to your controller, where you’ll return a list of cities based on the
selected state.  Your Cities dropdown will also be hidden at the start, but will be revealed once a country is selected.  Also, you don’t want to return a model based on your two lists because a Create view needs to reserve a model specifically for the form
elements of the View.

public ActionResult Create()
{
  var states = db.Australiastates.ToList();

  ViewBag.stateList = states;

  return View();
}

In the above action, we create a list of States and pass them to the view as a ViewBag object.  We do NOT return any model to the view.

Now we create the View:

@model AppName.Models.YourFormModel

@section scripts {
  <script type="text/javascript">
    $("#Cities").hide();

    $("#States").on("change", function () {

// make the get-request
$.getJSON('@Url.Action("GetCities")', { id: $(this).val() }, function (cities) {

// populate the Cities dropdown with returned data
$.each(cities, function (i, city) {
$("#Cities").append('<option value="' + city.AustraliaCityId + '">' + city.AustraliaCityName + '</option>');
});

});

// show the Cities dropdown
$("#Cities").show();

}); </script> } <div> @Html.DropDownList("States", new SelectList(ViewBag.stateList, "AustraliaStateId", "AustraliaStateName"), "Select a state") </div> <div> <select id="Cities" /> </div>

In the above view, we have a dropdown list for both States and Cities, however you’ll notice that the Cities dropdown list is just a generic <select> element.  This is because we didn’t initially pass any data from the Create action to the view, so there’s
no reason to have the DropDownList helper.  We also have a "scripts-section" at the top, with a <script> block and some code inside.  The code is jQuery.  the first line hides our Cities dropdown because it will initially be empty, so it doesn’t need to be
shown immediately.  The 2nd part of the script is an on-change event for the States dropdown list.  On-change, we make a call to an action named "GetCities" where we pass an "id" param of the states dropdown value.  The action will use this param to find all
cities associated with the ID and return it back to the View.  Once the data is returned, we populate the Cities dropdown list, and then show the dropdown list so it can be visible.

Next, we need to add the "GetCities" action to take the State ID and return a list of Cities:

[HttpGet]
public ActionResult GetCities(int id)
{
  var cities = db.AustraliaCities.Where(c => c.State_ID == id).ToList();

  return Json(cities, JsonRequestBehavior.AllowGet);
}

This action should be fairly obvious.  We used the state’s ID to gather a list of cities.  The only issue I had with this is that I didn’t see a "StateID" property in your AustraliaCities model, though I feel there should be one to create an association
between City and State.  I’ll let you determine how to use the state’s ID in the action to populate your Cities list.  In any case, once you have your list of cities, you return it as a JSON result.

That’s all there is to it.  This is a complete working solution.  Please let me know if you have questions.

Hi athelli_,

Thanks for your post.

athelli_reddy

Need help to create Cascading DropDownList using MVC4 – C# from Database

You can use JQuery, Please refer to this link:

#Creating cascading dropdownlists using MVC 4 And JQuery

http://jnye.co/Posts/12/creating-cascading-dropdownlists-using-mvc-4-and-jquery

Hope this can be helpful.

Best Regards,

Eileen

Thank you very much John for detailed explanation & your solution is working.

Can you please let me know how can I make State Dropdown menu field as a Mandatory field and show a client side validation if when the dropdown contains "Select a state" value.

public class AustraliaStates
    {
        [Key]
        public string AustraliaStateId { get; set; }
        
        [Required]  ->what else I can add here to make it as a Mandatory if there is "Select a state" value
        public string AustraliaStateName { get; set; }
    }

or do I need to write any java script??

[RESOLVED]why my helper havent any output after run !!!!!!

Hi dear,

I‘ve created
a method and
run it
. But
this method
does not
output
. So I
trace the code
and found
the body of a method
is not implemented.
I do not know
why
.
Please give me
what’s problem.

my code:

 @helper SetName(string name)
                {
                          string first_name = name;
                          <label>@first_name</label>
                      
    
                }
---------------run helper ----
  SetName("asp.net");

 

how can i solve this problem

 @helper SetName(string name)
 {
     <label>@name</label>
 }

That should be all you need. If you want it to render, you should call it like this (prefix with @):

@SetName("asp.net")

Mikesdotnetting

 @helper SetName(string name)
 {
     <label>@name</label>
 }

That should be all you need. If you want it to render, you should call it like this (prefix with @):

@SetName("asp.net")

thank you very veryyyy much Mikesdotnett

[RESOLVED]How to Post with foreign keys

public List<Job> PostNewJob(Job newJob)
        {
            Job job = new Job();

            job.JobId = newJob.JobId;
            job.JobNumber = newJob.JobNumber;
            job.JobName = newJob.JobName;
            job.JobDescription = newJob.JobDescription;
           
            db.Jobs.Add(newJob);
            db.SaveChanges();

            return db.Jobs.ToList();
        }

 public class Job
    {
        public Job()
        {
            this.Customers = new HashSet<Customer>();
            this.ChangeOrders = new HashSet<ChangeOrder>();
        }
        public int JobId { get; set; }
        public int JobNumber { get; set; }
        public string JobName { get; set; }
        public string JobDescription { get; set; }

        public virtual ICollection<Customer> Customers { get; set; }
        public virtual ICollection<ChangeOrder> ChangeOrders { get; set; }
    }


public List<Customer> PostNewCustomer(Customer newCustomer)
        {
            Customer customer = new Customer();

            customer.CustomerId = newCustomer.CustomerId;
            customer.CustomerName = newCustomer.CustomerName;
            customer.CustomerPhoneNumber = newCustomer.CustomerPhoneNumber;
            customer.CustomerFaxNumber = newCustomer.CustomerFaxNumber;
            customer.JobId = newCustomer.JobId;

            db.Customers.Add(newCustomer);
            db.SaveChanges();

            return db.Customers.ToList();
        }

 public class Customer
    {

        public int CustomerId { get; set; }
        public string CustomerName { get; set; }
        public Int64 CustomerPhoneNumber { get; set; }
        public Int64 CustomerFaxNumber { get; set; }

        public int? JobId { get; set; }
    }


 $scope.submitJob = function () {
        var id = $scope.currentItem.JobName
        var data = {
            JobId: $scope.currentItem.JobId,
            JobNumber: $scope.currentItem.JobNumber,
            JobName: $scope.currentItem.JobName,
            JobDescription: $scope.currentItem.JobDescription
            
            
        }
        $http.post('/api/apiJob/PostNewJob', data).success(function (data, status, headers) {
            console.log(data);
               $scope.PrintPreviewModal();
               window.top.location.reload();
            
        });
 };

  <form ng-submit="submitJob()" enctype="multipart/form-data">
                            <fieldset>
                                <div>
                                    <div class="inline-fields">
                                        <label>Number:</label>
                                        <input ng-model="currentItem.JobNumber" type="text">

                                        <label>Job Name:</label>
                                        <input ng-model="currentItem.JobName" type="text">
                                        <label>Customer:</label>
                                        <input type="text" ng-model="currentItem.CustomerName">
                                    </div>
                                    <div class="inline-fields">
                                        <label>Address:</label>
                                        <input ng-model="currentItem.CustomerAddress" type="text">
                                    </div>
                                    <div class="inline-fields">
                                        <label>City:</label>
                                        <input ng-model="currentItem.CustomerCity" type="text">

                                        <label>St:</label>
                                        <input ng-model="currentItem.CustomerState" type="text">

                                        <label>Zip:</label>
                                        <input ng-model="currentItem.CustomerZipcode" type="text">

                                <input type="submit" value="Save" />

                            </fieldset>
                        </form>

I am trying to change how I post and update my primary class JOB. Previously I was using the Customer Class as a List and I was storing the JOB Customer information in the Job class itself. The problem with this was If I went to go update a Customers information
in the Customer List I would have to go to every Job that has that Customer and Manually update everyone separately. So I am unsure how to do this. When I am creating a New Job how do I  Connect the appropriate Customer with that Job? I am already doing this
with another class called ChangeOrder but the difference is the Job has to be already been created before I can make that Post.. And also, the Customer can be assigned to multiple Jobs. So How does the foreign key work with this? How can you have a Customer
with multiple foreign keys "JobIds" attached to it?

What you are looking is a many to many relationship. Please take a look at this article in MSDN magazine

Handle Many-to-Many Relationships in Entity Framework and ASP.NET MVC

ok, so I created a linking table. What am I doing wrong? Here is what is coming back from the database

 {$id:1, JobCustomerId:1, JobId:1, Job:null, CustomerId:2, Customer:null}
$id: "1"
Customer: null
CustomerId: 2
Job: null
JobCustomerId: 1
JobId: 1

public class JobCustomer
    {
        public int JobCustomerId { get; set; }
        public int JobId { get; set; }
        public virtual Job Job { get; set; }
        public int CustomerId { get; set; }
        public virtual Customer Customer { get; set; }
    }
public class Job
    {
       
        public int JobId { get; set; }
        public int JobNumber { get; set; }
        public string JobName { get; set; }
        public string JobDescription { get; set; }

        public ICollection<JobCustomer> JobCustomers { get; set; }
       
    }
public class Customer
    {

        public int CustomerId { get; set; }
        public string CustomerName { get; set; }
        public Int64 CustomerPhoneNumber { get; set; }
        public Int64 CustomerFaxNumber { get; set; }

        public ICollection<JobCustomer> JobCustomers { get; set; }
      }
public List<JobCustomer> GetJobs()
        {
            List<JobCustomer> jobs = new List<JobCustomer>();
             jobs = db.JobCustomers
                .ToList();
            return jobs;
        }

Hi texas697,

You don’t need to create a link table manually, the EF will create it. For the link table, it doesn’t have the entity field, just the keys of these entities.

For your code, the fluent API would be like this:

modelBuilder.Entity<Job>() 
    .HasMany(j => j.Customers) 
    .WithMany(c => c.Jobs) 
    .Map(m => 
    { 
        m.ToTable("JobCustomer"); 
        m.MapLeftKey("JobId"); 
        m.MapRightKey("CustomerId"); 
    });
public class Job
    {
       
        public int JobId { get; set; }
        public int JobNumber { get; set; }
        public string JobName { get; set; }
        public string JobDescription { get; set; }

        public ICollection<Customer> Customers { get; set; }
       
    }
public class Customer
    {

        public int CustomerId { get; set; }
        public string CustomerName { get; set; }
        public Int64 CustomerPhoneNumber { get; set; }
        public Int64 CustomerFaxNumber { get; set; }

        public ICollection<Job> Jobs { get; set; }
      }

More information, please refer to:

# Configuring a Many-to-Many Relationship

http://msdn.microsoft.com/en-in/data/jj591620.aspx#ManyToMany

Best Regards

Starain Chen

that sure does make things easier. Now what if I have additional classes that need to be linked to Job? How would the modelBuilder look? Do i put this in my IdentityModels? If this is the correct way of doing it, I did do a migration without errors. The
tables in the sql where created. But How Do I query the information from my project? I went through the JobApi but the data for Customers, ChangeOrders, etc… came back null. 

 public class ApplicationUser : IdentityUser
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public bool? Hidden { get; set; }
        public string UserEmail { get; set; }
    }

    public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
    {
        public ApplicationDbContext()

            : base("DefaultConnection", throwIfV1Schema: false)
        {
            this.Configuration.LazyLoadingEnabled = false;
            this.Configuration.ProxyCreationEnabled = false;

        }
        public DbSet<Job> Jobs { get; set; }

        public DbSet<Employee> Employees { get; set; }
        public DbSet<Customer> Customers { get; set; }
        public DbSet<ChangeOrder> ChangeOrders { get; set; }
        public DbSet<JobType> JobTypes { get; set; }
        public DbSet<GeoArea> GeoAreas { get; set; }
        public DbSet<JobClass> JobClasses { get; set; }

        protected override void OnModelCreating
       (DbModelBuilder modelBuilder)
        {
base.OnModelCreating(modelBuilder); modelBuilder.Entity<Job>() .HasMany(j => j.Customers) .WithMany(c => c.Jobs) .Map(m => { m.ToTable("JobCustomer"); m.MapLeftKey("JobId"); m.MapRightKey("CustomerId"); }); modelBuilder.Entity<Job>() .HasMany(j => j.ChangeOrders) .WithMany(c => c.Jobs) .Map(m => { m.ToTable("JobChangeOrder"); m.MapLeftKey("JobId"); m.MapRightKey("ChangeOrderId"); }); modelBuilder.Entity<Job>() .HasMany(j => j.GeoAreas) .WithMany(c => c.Jobs) .Map(m => { m.ToTable("JobGeoArea"); m.MapLeftKey("JobId"); m.MapRightKey("GeoAreaId"); }); modelBuilder.Entity<Job>() .HasMany(j => j.JobTypes) .WithMany(c => c.Jobs) .Map(m => { m.ToTable("JobJobType"); m.MapLeftKey("JobId"); m.MapRightKey("JobTypeId"); }); modelBuilder.Entity<Job>() .HasMany(j => j.JobClasses) .WithMany(c => c.Jobs) .Map(m => { m.ToTable("JobJobClass"); m.MapLeftKey("JobId"); m.MapRightKey("JobClassId"); }); } }

 public class Job
    {
       
        public int JobId { get; set; }
        public int JobNumber { get; set; }
        public string JobName { get; set; }
        public string JobDescription { get; set; }

        
        public ICollection<Customer> Customers { get; set; }
        public ICollection<ChangeOrder> ChangeOrders { get; set; }
        public ICollection<GeoArea> GeoAreas { get; set; }
        public ICollection<JobClass> JobClasses { get; set; }
        public ICollection<JobType> JobTypes { get; set; }
    }

Hi texas697,

Your code is right.

To load the related entities, we could use Include method.

For example:

var data =db.Jobs.Include("Customers");

Best Regards

Starain Chen

[RESOLVED]How to display a default value in Cascading DropDownList using Java Script and MVC4

I have 2 Cascading DropDownLists (State and Cities) .

I populate cities when I select a State.

In the Cities Dropdown list, the default value is not displayed but all the related Cities are displayed.

Can someone please help to populate a default value in Cities Dropdown list?

The following is my model for State and Cities DropDown list

public class AustraliaStates
    {
        [Key]
        [Required]
        public string AustraliaStateId { get; set; }
        [Required]
        public string AustraliaStateName { get; set; }
    }

    public class AustraliaCities
    {
        [Key]
        [Required]
        public string AustraliaCityId { get; set; }

        [Required]
        public string AustraliaCityName { get; set; }
        
        [Required]
        public string AustraliaStateId { get; set; }
        
    }

Accommodation View.cshtml

      <form name="datapluspics" method="post" enctype="multipart/form-data">
                    @Html.ValidationSummary(true)
                    <fieldset>
                    @*Form Display Table START here*@
                    <table class="FormTableStyle" >
                                                
                        <tr>
                            <td class="FormDisplayLeftTableStyle">
                                <div class="editor-label">
                                    @Html.LabelFor(model => model.Suburb)
                                </div>
                            </td>
                            <td class="FormDisplayRightTableStyle">
                                <div class="editor-field">
                                    : @Html.EditorFor(model => model.Suburb)
                                    @Html.ValidationMessageFor(model => model.Suburb)
                                </div>
                            </td>    
                        </tr>

                        <tr>
                            <td class="FormDisplayLeftTableStyle">
                                <div class="editor-label">
                                    @Html.LabelFor(model => model.State)
                                </div>
                            </td>

                            <td class="FormDisplayRightTableStyle">
                                <div class="editor-field">
                                            <div>
                                             : @Html.DropDownListFor(model => model.SelectedAustraliaStateId, Model.AustraliaStates, "Select a state", new { id = "States", @class = "DropDownFieldStyle" })
                                             @Html.ValidationMessageFor(model => model.SelectedAustraliaStateId)
                                </div>
                            </td>    
                        </tr>

                        <tr>
                            <td class="FormDisplayLeftTableStyle">
                                <div class="editor-label">
                                    @Html.LabelFor(model => model.City)
                                </div>
                            </td>
                            <td class="FormDisplayRightTableStyle">
                                <div class="editor-field">
                                    : @Html.DropDownListFor(model => model.SelectedAustraliaCityId, Model.AustraliaCities, "Select a City", new { id = "Cities", @class = "DropDownFieldStyle" })
                                </div>
                            </td>    
                        </tr>

</table> 
                    </fieldset>
                    @*Form Display Table END here*@
                
                </form>

Here is the JS script

@section Scripts {

                    <script type="text/javascript">
                        $("#Cities").hide();

                        $("#States").on("change", function () {

                            var cityDropdown = $('#Cities');
                            cityDropdown.empty();

                            $.getJSON('@Url.Action("GetCities")',
                            { id: $(this).val() },
                            function (cities) 
                            {
                                $.each(cities, function (i, city) 
                                {
                                    $("#Cities").append('<option value="' + city.AustraliaCityId + '">' + city.AustraliaCityName + '</option>');
                                });

                            });


                            $('#Cities').show();

                        });
                    </script>

                }

GetCities Action in Controller:

[HttpGet]
        public ActionResult GetCities(string id)
        {
            var cities = db.AustraliaCities.Where(c => c.AustraliaStateId == id).ToList();

            return Json(cities, JsonRequestBehavior.AllowGet);
        }

Can someone please help me?

Here is my site: http://overseasindians.com.au/

@section Scripts {

                    <script type="text/javascript">
                        $("#Cities").hide();

                        $("#States").on("change", function () {

                            var $cityDropdown = $('#Cities');
                            $cityDropdown.empty();

                            $.getJSON('@Url.Action("GetCities")',
                            { id: $(this).val() },
                            function (cities) 
                            {
                                $cityDropdown.append('<option value="">Select One...</option>').val("");
                                $.each(cities, function (i, city) 
                                {
                                    $cityDropdown.append('<option value="' + city.AustraliaCityId + '">' + city.AustraliaCityName + '</option>');
                                });

                            });


                            $cityDropdown.show();

                        });
                    </script>

                }

Hope this helps. it’s not tested, but you should catch the idea.

[RESOLVED]How comes i cant get my 3 dropdownlist value?

Hi, i am trying to put 3 dropdownlist DAY , MONTH, YEAR in  stead of a single field : DateOfBirth

I modify my register view page  Account/Register.cshtml  like this :

        <div class="form-group">
            @Html.LabelFor(m => m.DateOfBirth, new { @class = "col-md-4 control-label" })
            <div class="col-md-8">
                @Html.DropDownList("DateOfBirthDay", Enumerable.Range(1, 31).Select(i => new SelectListItem { Value = i.ToString(), Text = i.ToString() }), "-- Select Day --")
                @Html.DropDownList("DateOfBirthMonth", Enumerable.Range(1, 12).Select(i => new SelectListItem { Value = i.ToString(), Text = System.Globalization.CultureInfo.InvariantCulture.DateTimeFormat.GetMonthName(i) }), "-- Select Month --")
                @Html.DropDownList("DateOfBirthYear", Enumerable.Range(1900, 109).Select(i => new SelectListItem { Value = i.ToString(), Text = i.ToString() }), "-- Select Year --")
                @Html.ValidationMessageFor(m => m.DateOfBirth)
            </div>
        </div>

I updated my controller with the following :

 //
        // POST: /Account/Register
        [HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        public async Task<ActionResult> Register([Bind(Include = "DateOfBirthDay,DateOfBirthMonth,DateOfBirthYear")] RegisterViewModel model)

this is my  RegisterViewModel : (AccountViewModels.cs)

 public class RegisterViewModel
    {
        [Required(ErrorMessageResourceName = "Required", ErrorMessageResourceType = typeof(ViewRes.ValidationStrings))]
        [DataType(DataType.EmailAddress)]
        [RegularExpression(@"^([a-zA-Z0-9_-.]+)@(([[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.)|(([a-zA-Z0-9-]+.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(]?)$", ErrorMessageResourceName = "Invalid", ErrorMessageResourceType = typeof(ViewRes.ValidationStrings))]
        [Display(Name = "UserName", ResourceType = typeof(ViewRes.Names))]
        public string UserName { get; set; }

        [Required(ErrorMessageResourceName = "Required", ErrorMessageResourceType = typeof(ViewRes.ValidationStrings))]
        [StringLength(100, ErrorMessageResourceName = "PasswordMinLength", ErrorMessageResourceType = typeof(ViewRes.ValidationStrings), MinimumLength = 6)]
        [DataType(DataType.Password)]
        [Display(Name = "Password", ResourceType = typeof(ViewRes.Names))]
        public string Password { get; set; }

        [DataType(DataType.Password)]
        [Display(Name = "ConfirmPassword", ResourceType = typeof(ViewRes.Names))]
        [Compare("Password", ErrorMessageResourceName = "PasswordMustMatch", ErrorMessageResourceType = typeof(ViewRes.ValidationStrings))]
        public string ConfirmPassword { get; set; }

        // New Fields added to extend Application User class:
        [Required(ErrorMessageResourceName = "Required", ErrorMessageResourceType = typeof(ViewRes.ValidationStrings))]
        [Display(Name = "FirstName", ResourceType = typeof(ViewRes.Names))]
        public string FirstName { get; set; }

        [Required(ErrorMessageResourceName = "Required", ErrorMessageResourceType = typeof(ViewRes.ValidationStrings))]
        [Display(Name = "LastName", ResourceType = typeof(ViewRes.Names))]
        public string LastName { get; set; }

        [Required(ErrorMessageResourceName = "Required", ErrorMessageResourceType = typeof(ViewRes.ValidationStrings))]
        [Display(Name = "Sex", ResourceType = typeof(ViewRes.Names))]
        public string Sex { get; set; }

        [Required(ErrorMessageResourceName = "Required", ErrorMessageResourceType = typeof(ViewRes.ValidationStrings))]
        [Display(Name = "DateofBirth", ResourceType = typeof(ViewRes.Names))]
        [DataType(DataType.DateTime)]
        [DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]
        public DateTime DateOfBirth { get; set; }

        public DateTime DateOfRegistration { get; set; }

        public bool UserNewsletter { get; set; }

        public string DefaultLanguage { get; set; }

        public string RealUserLanguage { get; set; }
        
        // Return a pre-poulated instance of AppliationUser:
        public ApplicationUser GetUser()
        {
            //Generate random code
            string randomcode = "";
            Random random = new Random();
            int length = 8;
            for (int i = 0; i < length; i++)
            {
                if (random.Next(0, 3) == 0)                     //if random.Next() == 0 then we generate a random character
                {
                    randomcode += ((char)random.Next(65, 91)).ToString();
                }
                else                                            //if random.Next() == 0 then we generate a random digit
                {
                    randomcode += random.Next(0, 9);
                }
            }



            //Get the language of the user
            string defaultlanguage = "en";
            string langName = "en";
            if (HttpContext.Current.Request.UserLanguages != null && HttpContext.Current.Request.UserLanguages.Length != 0)
            {

                defaultlanguage = HttpContext.Current.Request.UserLanguages[0].Substring(0, 2);

                if (defaultlanguage == "it")
                {
                    langName = "it";
                }
                if (defaultlanguage == "fr")
                {
                    langName = "fr";
                }
                if (defaultlanguage == "es")
                {
                    langName = "es";
                }

            }



            var user = new ApplicationUser()
            {

                UserName = this.UserName,

                FirstName = this.FirstName,

                LastName = this.LastName,

                Sex = this.Sex,

                DateOfBirth = this.DateOfBirth,

                DateOfRegistration = DateTime.Now,

                PasswordNotHashed = this.ConfirmPassword,

                CodeVerification = randomcode,

                UserActive = true,

                UserNewsletter = this.UserNewsletter,

                DefaultLanguage = langName,

                RealUserLanguage = defaultlanguage,

            };
            return user;
        }
    }

But when i try to get the 3 dropdownlist data in my controller it looks like they don’t exist… why?

example

 DateOfBirthYear = model.DateOfBirthYear;

Thanks

Hi,

Either you can go for Strongly Typed DropdownListFor or if you want to stick for the same code then you can pass the parameters in your post method like below -

YourPostMethod(string DateOfBirthDay , string DatehOfBirthMonth, string DateOfBirthYear)

{



}

Hi, like this i can see them, but how can i make them as a required fields?

because, when i register,  if i don’t choose any day or month or year i get error :

Erreur du serveur dans l'application '/'.

La chaîne n'a pas été reconnue en tant que DateTime valide.

Description : Une exception non gérée s'est produite au moment de l'exécution de la requête Web actuelle. Contrôlez la trace de la pile pour plus d'informations sur l'erreur et son origine dans le code. 

Détails de l'exception: System.FormatException: La chaîne n'a pas été reconnue en tant que DateTime valide.

Erreur source: 


Ligne 820 :                {
Ligne 821 :                    // do for invalid date
Ligne 822 :                    DateTime FullDateOfBirthLastFormatDate = Convert.ToDateTime(FullDateOfBirthLast);
Ligne 823 :                    user.DateOfBirth = FullDateOfBirthLastFormatDate;
Ligne 824 :

you should add the three down drown fields to the view model and make them required.

[RESOLVED]Asp.net MVC Controller / Model Quandry

Consider the following two Models: AModel
(Class A)
 and BModel
(Class B)
, and two partial views:AView
(bound to AModel)
 and BView
(bound to BModel)
.

I have a Controller called TestController.
In TestController I
have the following methods:

<HttpPost>
Function Index(model as AModel) As ActionResult
    Return View(model)
End Function

<HttpPost>
Function Index(model as BModel) As ActionResult
    Return View(model)
End Function

In Index I
have the following code:

@Using Html.BeginForm()
@<div>
    @Html.Partial("~/Views/Test/AView.vbhtml")  ' this is here for test only
    <div><input type="submit" name="submit" value="Submit" /></div>
</div>
End Using

My partial views look like this:

@ModelType Company.Domain.Models.ModelA '(or ModelB for the other)

<div>@Html.LabelFor(Function(m) m.Name)</div>
<div>@Html.TextBoxFor(Function(m) m.Name)</div>

... and so on, several Input fields follow ...

When I fill in and submit AView I get the following error:

The current request for action 'Index' on controller type 'TestController' is ambiguous between the following action methods:
System.Web.Mvc.ActionResult Index(Company.Domain.Models.AModel) on type Company.WebUI.Controllers.TestController
System.Web.Mvc.ActionResult Index(Company.Domain.Models.BModel) on type Company.WebUI.Controllers.TestController

After some research I tried putting <ActionName("Index")> over
each Index method in TestController but
generates the same error (I changed the method names to AIndex and BIndexthen
placed the action name attribute above them and tested
.)

What I’m trying to achieve: I have two forms I need my user to fill out (one after the other). Each form has it’s own set of properties and validation (naturally), hence AModel and BModel. I created two matching Partial Views (partial because I
will want to use those views within other main views later on).

I’m lost as to how to achieve what I want here because ASP.NET isn’t recognizing the different method signatures, nor am I sure I’m going about doing this correctly under ASP.NET MVC anyway. Under a competing platform I would simply #INCLUDE my
pages as needed.

I hope my explanation is clear, appreciate any advice.

put the names of the 2 actions as IndexA and IndexB

Html.BeginForm supports adding action name

ASP.NET MVC Controllers do not support overloading Controller Actions (e.g. you cannot have two Actions with the same name that expect the same type of request like POST).

Using an ActionName attribute

You really have two options here. You could explitly change the name of each of your actions :

<HttpPost>
Function A(model as AModel) As ActionResult
    Return View("Index",model)
End Function

<HttpPost>
Function B(model as BModel) As ActionResult
    Return View("Index",model)
End Function

Or you can explicitly set a name for the action using an [ActionName] attribute :

<HttpPost>
<ActionName("A")>
Function Index(model as AModel) As ActionResult
    Return View("Index",model)
End Function

<HttpPost>
<ActionName("B")>
Function Index(model as BModel) As ActionResult
    Return View("Index",model)
End Function

You obviously don’t need to assign an ActionName to both of them, but at least one will need it in order differentiate between the two.

Ensuring Proper Posting

Another issue here is that ASP.NET MVC is not going to know which particular Action that you are trying to POST to from your form unless you explicitly specify it within the BeginForm() Helper method :

@Using Html.BeginForm("A","Test")
@<div>
    @Html.Partial("~/Views/Test/AView.vbhtml")  ' this is here for test only
    <div><input type="submit" name="submit" value="Submit" /></div>
</div>
End Using

If you use the ActionName attributes mentioned above (or simply rename the Action), this should now refer to the "A" method and will POST your "A" Model to the appropriate action. If you are going to be setting some of these values dynamically (such
as an AJAX call
), then you’ll likely want to include the <form> itself within the Partial Views to avoid any confusion of where to POST to.

[RESOLVED]How to use ajax script to prevent from postback view when saving records into the database?

I have a controller which I used to save records into the database. I noticed that everytime the I save a record the entire view will flicker or postback. So I researched and I realized that I need to use a PartialViewand
an 
AJAX script to avoid from view postback. So far, what I’ve got are the details below but somehow I encountered trouble using them. Using the details below, when you post a comment, the div element named"ajaxcom" in
the view where my initial comments are displayed will be gone and the comments were not even saved anymore into the database but instead I want to display my partial view into the ajaxcom div element after when you click the 
Post Comments button
so that the entire view will not postback and just automatically displays the new comments within the ajaxcom div element. So I suspected there must have been something wrong with my ajax script below. How do I fix this? and what am I been missing?…Thanks

AJAX Script:

$(function () {

            $("#addcomment").on("submit", function (e) {
               e.preventDefault();

                $.ajax({
                  url: this.action,

                  type: this.method,

                 data: $(this).serialize(),

                    success: function (data) {
                     // ajaxcom is the id of the div element where I want to display my partialview 
                        $("#ajaxcom").html(data);

                    }
                });
            });
        });

Controller:

[HttpPost]
    public  ActionResult AjaxComments(CommentModel com)
    {

                if (ModelState.IsValid)
                {
                    comrepository.InsertComment(com); //this is to insert the records
                }
                  var vModel = new CreateViewModel();

                vModel.Comments = comrepository.GetAllComments().ToList();

                // AddComments is my partialview
                return PartialView("AddComments", vModel);

    }

View:

@using (Html.BeginForm("AjaxComments", "Profile", FormMethod.Post, new { id = "addcomment" }))
 {
    <fieldset>
        <legend>CommentModel</legend>

        <div class="editor-label">
           <label for="name">Name</label>
        </div>
        <div class="editor-field">

       <input type="text" id="name" name="name" />
       <span class="field-validation-valid" data-valmsg-for="name" data-valmsg-replace="true"></span>
        </div>

        <div class="editor-label">
            <label for="comment">Post your Comment here:</label>
        </div>
      <div class="editor-field" style="margin-bottom:0px">
      <textarea id="comment" name="comment" style="width:500px;height:100px;resize:none"  aria-multiline="True"></textarea>
      <span class="field-validation-valid" data-valmsg-for="comment" data-valmsg-replace="true"></span>
        </div>

        <p>
             <input type="submit" value="Post Comments" name="butname" />   

        </p>

        <br />

    </fieldset>

 }
    <h2>Comments</h2>
     <br />

  <div id="ajaxcom"> <!-- Div element to be invoked by ajax script  -->

  <table id="mytable">  

  @foreach (var item in Model.Comments )
      {
    <tr >
        <td class="tdstyle" >

  <div style="font-weight:bold;">  @Html.DisplayFor(modelItem => item.name) </div> 

   <p class="comment more" style ="white-space: pre-line; margin-top:0px;margin-bottom:0px; border-radius: 4px 4px 4px 4px; max-width :500px; min-height :5px;  display :block; background-color: #CCCCFF">  @Html.DisplayFor(modelItem => item.comment) </p>
  <p style="margin-top:2px;margin-bottom:0px"> <input type="button" id="like" name="like" value="Like" style="color:blue;border:0px;background-color:inherit;cursor:pointer" /> <input type="button" class ="Reply" name="Reply" value="Replie(s)"  style="margin-bottom:0px;color:blue;border:0px;background-color:inherit;cursor:pointer" /></p>


        </td>       
    </tr>

    }

</table>
 </div>

Hi timmack,

Please add a new partial view to display the comment details (e.g. CommentDetail.cshtml).

<table id="mytable">  

  @foreach (var item in Model.Comments )
      {
    <tr >
        <td class="tdstyle" >

  <div style="font-weight:bold;">  @Html.DisplayFor(modelItem => item.name) </div> 

   <p class="comment more" style ="white-space: pre-line; margin-top:0px;margin-bottom:0px; border-radius: 4px 4px 4px 4px; max-width :500px; min-height :5px;  display :block; background-color: #CCCCFF">  @Html.DisplayFor(modelItem => item.comment) </p>
  <p style="margin-top:2px;margin-bottom:0px"> <input type="button" id="like" name="like" value="Like" style="color:blue;border:0px;background-color:inherit;cursor:pointer" /> <input type="button" class ="Reply" name="Reply" value="Replie(s)"  style="margin-bottom:0px;color:blue;border:0px;background-color:inherit;cursor:pointer" /></p>


        </td>       
    </tr>

    }

</table>
[HttpPost]
    public  ActionResult AjaxComments(CommentModel com)
    {

                if (ModelState.IsValid)
                {
                    comrepository.InsertComment(com); //this is to insert the records
                }
                  var vModel = new CreateViewModel();

                vModel.Comments = comrepository.GetAllComments().ToList();

                // AddComments is my partialview
                return PartialView("CommentDetail", vModel);

    }

Best Regards

Starain Chen

I would suggest you to use MVC ajax, instead of jquery ajax. You are using jquery ajax, which also works but there is some problem in the way you are calling i guess the url, and data are not correct.

Replace html forms with ajax forms and remove the javascript function. verify how it works.

@using (Html.BeginForm("AjaxComments", "Profile", FormMethod.Post, new { id = "addcomment" }))

@using (Ajax.BeginForm("AjaxComments", "Profile", new { id = "addcomment" }, new AjaxOptions { UpdateTargetId = "ajaxcom", HttpMethod = "POST", InsertionMode = InsertionMode.Replace }))

 

[RESOLVED]datepicker work once in partialview mvc5

Hi,I’m having this annoying problemwith datepicker.
I’m working with MVC5, Bootstrap, jquery 1.10.2 and jquery-ui-1.11.1.
I have 2 datepickers in a partial view that is call it from a bs modal, and when I show the modal a second time, the datepicker stop working, and I’ve tried almost everything, take a look:

**JS Code**

<script type="text/javascript">
(function () {
$("#EDate").datepicker();
$("#RDate").datepicker({ minDate: "-1d" });

$("#divm").on("hidden.bs.modal", function () {
$(".datepicker").datepicker("destroy");
$(".datepicker").removeClass("hasDatepicker").removeAttr('id');
})
})();
</script>

**Razor Code**

@Html.EditorFor(model => model.EntryDateOperation, new { htmlAttributes = new { id = "EDate", @class = "form-control datepicker" } })
@Html.EditorFor(model => model.EntryDateOperation, new { htmlAttributes = new { id = "RDate", @class = "form-control datepicker" } })

**The bootstrap modal**

<div id="divm" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="Embarcaciones" aria-hidden="true">
<div class="modal-dialog" style="text-align:right">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<div style="text-align:left">
<h4 class="modal-title" id="mTitulo">Nueva Embarcaci&oacute;n</h4>
</div>
</div>
<div id="mEdit" class="modal-body" style="width:100%; text-align:center">
@{Html.RenderPartial("_myclass", Model.Myclass);}
</div>
</div>
</div>
</div>

**and I added z-index on jquery ui css**

.ui-datepicker {
width: 17em;
padding: .2em .2em 0;
display: none;
z-index: 9999999 !important;
}

As you can see I have tried almost everything, but I don’t know what else can I do, Thanks for any kind of help :)

lebarros

$(".datepicker").datepicker("destroy");

I believe this could be the problem. You are removing the date picker with the destroy method

[RESOLVED]Something is triggering unobtrusive validation, but what?

I have a fairly simple mvc form with validation.  One of the sections is a dynamically added partial view (add a new row with a button click).  Something in there is triggering a validation error, but I can’t find it.  It is requiring the IdentificationType
dropdown have a selected value, but as far as I can see, there is no "Required" set anywhere in the code.  There are 4 different sections setup as dynamiclly added partials and they are all fine.  The only difference I can see is the id type is a dropdown,
and it is the only one triggering the validation error.  Is this a dropdown thing?  Here is some code:

Partial view:

        <div class="IdentPartial" > 
             <div class="formGroup-Short">
                <div class="editor-label">
                    @*@Html.HiddenFor(m => m.IdentificationCounter, new { @class="iHidden" })*@
                    @Html.Label("Identification Type")
                </div>
                <div class="editor-field">
                     @Html.DropDownListFor(m => m.IdentificationModel[Model.IdentificationCounter].IdentificationType, new SelectList(Model.IDTypes, "Value", "Text"), "Select", new { style = "width: 150px;" })
                </div>
            </div>
        
            <div class="formGroup-Short">
                <div class="editor-label">
                    @Html.Label("Identification Number")
                </div>
                <div class="editor-field">
                    @Html.TextBoxFor(m => m.IdentificationModel[Model.IdentificationCounter].IdentificationNumber, new { style = "width:120px" })
                </div>
            </div>

            <div class="formGroup">
                <div class="editor-label"  style="width: 100px">
                    @Html.Label("Issuing State")
                </div>
                <div class="editor-field">
                    @Html.DropDownListFor(m => m.IdentificationModel[Model.IdentificationCounter].IssuingState, new SelectList(Model.State, "Value", "Text", "OR"), "Select", new { style = "width: 65px; margin-right:20px;" })
                </div>
            </div>
        </div>

ID Model:

    public class IdentificationMetadata
    {

        [DisplayName("Identification Type")]
        public string IdentificationType { get; set; }

        [DisplayName("Identification Number")]
        public string IdentificationNumber { get; set; }
        
        [DisplayName("State")]
        public string IssuingState { get; set; }
    }

jQuery script, button event:

            $("#AddId").on("click", function () {
                var itemIndex = $(".IdentPartial .iHidden").length;
                $.get(
                    "@Url.Action("NewIdentRow")/" + itemIndex,
                    function (data) {
                        $("#IdentDataSection").append(data);
                    });
            });

Can you send the exact error message you are getting it?

As far as i see you don’t have a required field in your model.

I finally found the solution, the IdentificationType was a not null int in the DB.  I made it nullable in the DB and changed it int he model, now if doesnt trigger the validation.