Tag Archives: Controller

Controller

pass model from View to Controller via AJAX – tried everything

Hello guys, 

I have tried everything trying to pass a model (from a strongly typed view) to a controller action using ajax and it always arrives empty, here is my code, please tell me what’s wrong with it (i have tried a variety of things tho and stll nothing has worked):

the model i am trying to pass is a ViewModel like this: (is the [Serializable] mandatory ?)

 [Serializable]
    public class RatingAreaViewModel
    {
        public int userId {get; set;}

        public double[] currentRating {get; set;}
        public double[] newUserRating { get; set; }

        public bool hasAlreadyVoted { get; set; }
        public double[] oldUserRating { get; set; }
        
        public int numberOfVotes { get; set; }

        public RatingAreaViewModel()
        {
            currentRating = new double[5] { 0, 0, 0, 0, 0 };
            newUserRating = new double[5] { 0, 0, 0, 0, 0 };
            oldUserRating = new double[5] { 0, 0, 0, 0, 0 };
        }

    }

and here is the ajax function in my view: 

  var obj = @Html.Raw(Model);
     
        function submitRating() {

            $.ajax({
                url: RootUrl + "Players/RatePlayer",
                type: 'POST',
                data: { object: JSON.Encode(obj) , vote1: vote1, vote2: vote2, vote3: vote3,vote4: vote4 },
                success: function (ratingAreaViewResult) {

                    alert("success");
                    document.getElementById("ratingArea").html(ratingAreaViewResult);
                },
                error: function (xhr) { alert("Something seems Wrong"); }
            });

        }
    

I have tried soo many combinations including JSON.Stringify and still the problem is that the model arrives empty at the controller (all zero values)

public ActionResult RatePlayer(RatingAreaViewModel ravm, int vote1,int vote2,int vote3,int vote4)
{

    // AT THIS POINT HERE ALL VOTES ARRIVE OK BUT THE MODEL ARRIVES EMPTY
    
return partialview(...); }

thank you a lot guys!!

try…

var obj = @Html.Raw(Json.Encode(Model));

// and then change the 'data' option to:

data: JSON.stringify({ "ravm": obj, "vote1": vote1, "vote2": vote2, ... }),
...

You need to stringify your JSON data

First refer the reply of John

also try this

aymane07

data: { object: JSON.Encode(obj) , vote1: vote1, vote2: vote2, vote3: vote3,vote4: vote4 },

data: { ravm: JSON.Encode(obj) , vote1: vote1, vote2: vote2, vote3: vote3,vote4: vote4 },

Pass your data like this in jquery ajax call.

data: $(‘#formName’).serialize() + "&vote1=" + vote1+ "&vote2=" + vote2

Hi aymane07,

Based on my test, to serialize the object to JSON string, we should to use
JavaScriptSerializer
class.

For your requirement, you need add the object to a JSON, then convert it to the JSON string.

Please refer to this code below to achieve your requirement:

 public class Field
    {
        [Required]
        public string DataInfo { get; set; }

        [Required]
        public string Value { get; set; }

        //[MustBeTrue(ErrorMessage="required")]
        public bool IsRequired { get; set; }

        [Required]
        public int serverIDTo { get; set; }

    }
 public ActionResult JqueryFormSubmit()
        {
            Field f=new Field(){ DataInfo="dataInfor1", IsRequired=true, serverIDTo=2, Value="value1" };
            return View(f);
        }
        [HttpPost]
        public string JqueryFormSubmit(Field f, string txtQues,FormCollection c)
        {
            string str = txtQues ?? "empty";
            if (f != null && !string.IsNullOrEmpty(f.DataInfo))
                str += f.DataInfo;
            else
                str += " and null";
            return str;    
        }
@model MvcDemo2.Models.Field

@{
    ViewBag.Title = "JqueryFormSubmit";
    var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
    string objJson=serializer.Serialize(Model);
}
 $(document).ready(function () {
            $('#btnSubmit').click(function () {
                var obj =JSON.parse('@Html.Raw(objJson)'); 
                var jsonData =JSON.parse(JSON.stringify({ f: {}, txtQues: "gg" }));
                //add object to json 
                jsonData.f = obj;
                 $.ajax({
                    url: '@Url.Action("JqueryFormSubmit")',
                    type: 'POST',
                    contentType:"application/json",
                    data: JSON.stringify(jsonData), 
                    success: function (data) {
                        //debugger;
                        alert(data);
                    },
                    error: function (response, xhr, data) {
                      }
                }
            )
            });
});

Best Regards

Starain Chen

What is this; formName ?? I think i don’t have any form in my View

Hello, 

I have tried your exact same code and it doesn’t work! all the votes are passed safely but the object is all zeros and falses :(:(:(

Is there something more basic i am missing…  here the code i tried exactly: 

[httppost] 
public ActionResult RatePlayer(RatingAreaViewModel ravm, int vote1,int vote2,int vote3,int vote4) { }

function submitRating() {

            var obj = JSON.parse('@Html.Raw(objJson)');
            var jsonData = JSON.parse(JSON.stringify({ f: {}, vote1: vote1, vote2: vote2, vote3: vote3, vote4: vote4 }));
            jsonData.f = obj;
            
            $.ajax({
                url: RootUrl + "Players/RatePlayer",
                type: 'POST',
                contentType: "application/json",
                data: JSON.stringify(jsonData),
                success: function (ratingAreaViewResult) {

                    alert("success");
                    document.getElementById("ratingArea").html(ratingAreaViewResult);
                },
                error: function (xhr) { alert("Something seems Wrong"); }
            });

        }


@{
    var url = Request.Url.AbsolutePath;
    var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
    string objJson = serializer.Serialize(Model);   
}


Please tell me i am missing something i am getting really crazy here :(:(

thanks a lot

Hello

JohnLocke

try…

var obj = @Html.Raw(Json.Encode(Model));

// and then change the 'data' option to:

data: JSON.stringify({ "ravm": obj, "vote1": vote1, "vote2": vote2, ... }),
...

You need to stringify your JSON data

Hello John, I have tried your code and it doesn’t work.. It doesn’t even compile at my end when I write this: 

var obj = @Html.Raw(Json.Encode(Model));

I have this error: IHTMLString returns markup that is not HTML…

cnuonline

First refer the reply of John

also try this

aymane07

data: { object: JSON.Encode(obj) , vote1: vote1, vote2: vote2, vote3: vote3,vote4: vote4 },

data: { ravm: JSON.Encode(obj) , vote1: vote1, vote2: vote2, vote3: vote3,vote4: vote4 },

Hello, I have tried your code and it doesn’t work.. can’t even get to the controller this way.. plz help

Hi aymane07,

For my code is just a sample. You need modify it.

Based on your code, a parameter name of your action (RatingAreaViewModel) is
ravm, so you need replace f to ravm.

 var jsonData = JSON.parse(JSON.stringify({ ravm: {}, vote1: vote1, vote2: vote2, vote3: vote3, vote4: vote4 }));
            jsonData.ravm = obj;
            

Best Regards

Starain Chen

Starain chen – MSFT

Hi aymane07,

For my code is just a sample. You need modify it.

Based on your code, a parameter name of your action (RatingAreaViewModel) is
ravm, so you need replace f to ravm.

 var jsonData = JSON.parse(JSON.stringify({ ravm: {}, vote1: vote1, vote2: vote2, vote3: vote3, vote4: vote4 }));
            jsonData.ravm = obj;
            

Best Regards

Starain Chen

Thanks for your reply.. I have done exactly what you asked, and it still doesn’t work :)

I have noticed an issue with my code, when i use ravm: {} the request doesn’t even get to the controller action, whereas when i do
object:{} the request gets to the controller action but the object is all zeros. 

Second thing i have noticed is a difference between our code, i am NOT using any form, so when you are saying url: Url.Action (form) i can’t say that, i just write the URL as a string (i don’t think this is causing the problem however).

Also, do you think i should be putting [Serializable] before my class definition of the object or not ? 

below is the working code that gets to the controller but with an emtpy project.. if you have anything else i can try please let me know.. 

thanks a lot!

function submitRating() {

            //var obj = 'Html.Raw(val)';

            var obj = JSON.parse('@Html.Raw(objJson)');
            var jsonData = JSON.parse(JSON.stringify({ object: {}, vote1: vote1, vote2: vote2, vote3: vote3, vote4: vote4 }));


            jsonData.object = obj;

            $.ajax({
                url: RootUrl + "Players/RatePlayer",
                type: 'POST',
                contentType: "application/json",
                data: JSON.stringify(jsonData),
                success: function (ratingAreaViewResult) {

                    alert("success");
                    document.getElementById("ratingArea").html(ratingAreaViewResult);
                },
                error: function (xhr) { alert("Something seems Wrong"); }
            });

        }


I gave up for now and just passed an int Id instead of the object and reconstructed the object back in the controller: I did it this way: 

 $.post(url, { userId: id, vote1: vote1, vote2: vote2, vote3: vote3, vote4: vote4 }, function (ratingAreaViewResult) {
                
                $('#ratingArea').html(ratingAreaViewResult);
            });

 BTW, when I pass only the object using this code, it works fine, but as soon as I add the integers the object fails to pass correctly:: there is some big elephant i am missing here!!

if you guys think of something please let me know::

thanks again

Hi aymane07,

aymane07

Second thing i have noticed is a difference between our code, i am NOT using any form, so when you are saying url: Url.Action (form) i can’t say that, i just write the URL as a string (i don’t think this is causing the problem however).

This code is used to generate the URL, the string of JqueryFormSubmit is just the action name. I am not using any form too.

aymane07

Also, do you think i should be putting [Serializable] before my class definition of the object or not ? 

If you are just using JavaScriptSerialize, you don’t need add Serializable attribute to the model class.

Please use the developer tool to check the send data.

On the other hand, please share your project on the OneDrive, we will check it.

Best Regards

Starain Chen

[RESOLVED]problem with show data in view

Hi

I use ckeditor for send new post and ( code snippet  plugin ) , when I send new post and return to see post i can’t  see code snippet >>

view >>

Help me to show best data . .  I want when read data from controller show code with default ( Picture >> 1 << ) 

omid.nasri

I want when read data from controller show code with default ( Picture >> 1 << ) 

PLease explain better. I did not understand your question – nor the picture.

Mr
ignatandrei

I read data from Controller ( public actionresult index() ) with foreach key Ok! >>

public actionresult index()

{

var Q = (from t in mvc.tbl_test where t.id == 1 select t).tolist();

return view(Q);

}

now : I have problem with show data , I want when read data if user use  ( code snippet plugin in ckeditor ) show like  ( default in pictures ).

helpppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppp

Hi omid.nasri,

Thanks for your post.

According to your description,

omid.nasri

I want when read data if user use  ( code snippet plugin in ckeditor ) show like  ( default in pictures ).

You can to implement insert code snippet functionality?like this:

If so ,you can refer to this:

#Insert code snippet in CKeditor

http://www.ingeniumweb.com/blog/post/insert-code-snippet-in-ckeditor/1213/

Hope this can be helpful.

Best Regards,

Eileen

Try removing the Html.Raw and see you are able to see the code. Also check the View Source to see that your code is in the source and not showing in the display.

[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]How to increase ScriptTimeout in MVC5

Hi, i got a problem when i try to upload an image bigger than 4,8 MB, the page goes in time out.. i guess…

error :

[HttpException (0x80004005): Maximum request length exceeded.]

I tryied to add this code in my web.config

<location path="Creation/CreationUpload">
    <system.web>
        <httpRuntime executionTimeout="1000"/>
    </system.web>
</location>

but it does not work

this is the code in my controller :

// POST: /Creation/CreationUpload
        // Afin de déjouer les attaques par sur-validation, activez les propriétés spécifiques que vous voulez lier. Pour 
        // plus de détails, voir  http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [Authorize]
        [ValidateAntiForgeryToken]
        public ActionResult CreationUpload([Bind(Include = "CreationId,CreationTitle,CreationPhotoBis")] Creation creation, IEnumerable<HttpPostedFileBase> files)
        {
            if (ModelState.IsValid)
            {
               
                
                // update each field manually
                foreach (var file in files)
                {
                    if (file != null)
                    {
                        if (file.ContentLength > 0)
                        {

                            var myuploadextension = Path.GetExtension(file.FileName);

                            if (myuploadextension.ToUpper() == ".JPEG" || myuploadextension.ToUpper() == ".JPG" || myuploadextension.ToUpper() == ".BMP" || myuploadextension.ToUpper() == ".PNG" || myuploadextension.ToUpper() == ".GIF")
                        {


                            var sizeMb = (file.ContentLength / 1024f) / 1024f; //file.contentlength is in bytes

                            var todaydate = DateTime.Now.ToShortDateString();
                            var todaydatefriendly = todaydate.ImageFriendly();
                            var myuploadiwthoutextension = Path.GetFileNameWithoutExtension(file.FileName);
                            var myuploadiwthoutextensionfriendly = myuploadiwthoutextension.ImageFriendly();
                            var UserId = User.Identity.GetUserId();

                            var fileName = todaydatefriendly + "-" + UserId + "-" + myuploadiwthoutextensionfriendly + myuploadextension;

                            var path = Path.Combine(Server.MapPath("~/Content/UserCreations"), fileName);
                            file.SaveAs(path);

                            //Language
                            var actualculturetocheck = "en";
                            var actualculture = this.Session["ActualCulture"];
                            if (actualculture != null)
                            {
                                actualculturetocheck = actualculture.ToString();
                            }

                            
                            //Ipaddress
                            var ipAddress = Request.ServerVariables["REMOTE_ADDR"] + " " + Request.UserHostAddress;

                            creation.UserId = User.Identity.GetUserId();
                            creation.CreationLanguage = actualculturetocheck;
                            creation.CreationVisible = true;
                            creation.CreationDelete = false;
                            creation.CreationDate = DateTime.Now;
                            creation.CreationIpAdress = ipAddress;
                            creation.CreationPhotoBis = fileName; //after add

                            db.Creations.Add(creation);
                            db.SaveChanges();



                        }


                        }
                    }
                }

                //UserId
                return RedirectToAction("CreationList", "Creation", new { UserId = User.Identity.GetUserId() });
            }

            return View(creation);
        }

what should i do to increase the ScriptTimeout in my contorller action?

FULL ERROR WHEN I TRY TO UPLOAD :

[HttpException (0x80004005): Maximum request length exceeded.]
   System.Web.HttpRequest.GetEntireRawContent() +9553280
   System.Web.HttpRequest.GetMultipartContent() +63
   System.Web.HttpRequest.FillInFormCollection() +165
   System.Web.HttpRequest.EnsureForm() +75
   System.Web.HttpRequest.get_Form() +12
   System.Web.HttpRequestWrapper.get_Form() +9
   System.Web.Mvc.HttpRequestExtensions.GetHttpMethodOverride(HttpRequestBase request) +121
   System.Web.Mvc.AcceptVerbsAttribute.IsValidForRequest(ControllerContext controllerContext, MethodInfo methodInfo) +37
   System.Web.Mvc.HttpPostAttribute.IsValidForRequest(ControllerContext controllerContext, MethodInfo methodInfo) +39
   System.Web.Mvc.ActionMethodSelectorBase.IsValidMethodSelector(ReadOnlyCollection`1 attributes, ControllerContext controllerContext, MethodInfo method) +54
   System.Web.Mvc.ActionMethodSelectorBase.RunSelectionFilters(ControllerContext controllerContext, List`1 methodInfos) +124
   System.Web.Mvc.ActionMethodSelectorBase.FindActionMethods(ControllerContext controllerContext, String actionName) +142
   System.Web.Mvc.ActionMethodSelectorBase.FindActionMethod(ControllerContext controllerContext, String actionName) +104
   System.Web.Mvc.Async.ReflectedAsyncControllerDescriptor.FindAction(ControllerContext controllerContext, String actionName) +54
   System.Web.Mvc.ControllerActionInvoker.FindAction(ControllerContext controllerContext, ControllerDescriptor controllerDescriptor, String actionName) +16
   System.Web.Mvc.Async.AsyncControllerActionInvoker.BeginInvokeAction(ControllerContext controllerContext, String actionName, AsyncCallback callback, Object state) +114
   System.Web.Mvc.Controller.<BeginExecuteCore>b__1c(AsyncCallback asyncCallback, Object asyncState, ExecuteCoreState innerState) +25
   System.Web.Mvc.Async.WrappedAsyncVoid`1.CallBeginDelegate(AsyncCallback callback, Object callbackState) +30
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +128
   System.Web.Mvc.Controller.BeginExecuteCore(AsyncCallback callback, Object state) +468
   System.Web.Mvc.Controller.<BeginExecute>b__14(AsyncCallback asyncCallback, Object callbackState, Controller controller) +18
   System.Web.Mvc.Async.WrappedAsyncVoid`1.CallBeginDelegate(AsyncCallback callback, Object callbackState) +20
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +128
   System.Web.Mvc.Controller.BeginExecute(RequestContext requestContext, AsyncCallback callback, Object state) +374
   System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.BeginExecute(RequestContext requestContext, AsyncCallback callback, Object state) +16
   System.Web.Mvc.MvcHandler.<BeginProcessRequest>b__3(AsyncCallback asyncCallback, Object asyncState, ProcessRequestState innerState) +52
   System.Web.Mvc.Async.WrappedAsyncVoid`1.CallBeginDelegate(AsyncCallback callback, Object callbackState) +30
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +128
   System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContextBase httpContext, AsyncCallback callback, Object state) +384
   System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContext httpContext, AsyncCallback callback, Object state) +48
   System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.BeginProcessRequest(HttpContext context, AsyncCallback cb, Object extraData) +16
   System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +301
   System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155

Thanks

grafic.web

[HttpException (0x80004005): Maximum request length exceeded.]

This error is related to the size of the uploaded file. You need to increase the Request length

 <system.webServer>
   <security>
      <requestFiltering>
         <requestLimits maxAllowedContentLength="1073741824" />
      </requestFiltering>
   </security>
 </system.webServer>

For IIS versions older than 7 use this

<configuration>
    <system.web>
        <httpRuntime maxRequestLength="1048576" />
    </system.web>
</configuration>

If you are going to be working with files that are larger than the default of 4MB, you’ll need to update the maxRequestLength within your
web.config to handle files of that size. This can be handled within the <system.web> section of your web.config or the <system.webServer> section if you want to handle it at the IIS level (both are probably a good idea).

It’s important to know that maxAllowedContentLength is measured in bytes and maximumRequestLength is measured in kilobytes when settings these values so you’ll need to adjust them accordingly if you plan on handling much larger files : 

<configuration>
    <system.web>
        <!-- This will handle requests up to 30MB -->
        <httpRuntime maxRequestLength="30720" timeout="3600" />
    </system.web>
</configuration>

<!-- IIS Specific Targeting (noted by the system.webServer section) -->
<system.webServer>
   <security>
      <requestFiltering>
         <!-- This will handle requests up to 30MB -->
         <requestLimits maxAllowedContentLength="31457280" />
      </requestFiltering>
   </security>
</system.webServer>

If you don’t see these sections within your existing web.config file, you’ll simply need to copy them in.

[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]Adding a new field in Register Page.Storing Data in DataBase

Hi, 

 I’m new to this,To start with i downloaded a wingtip web asp.net sample. I want to include a new field ‘EMPLOYEEID" in register page and store the data in AspNetUsers database table. I have created the field in Register page and a new column in database(Aspnetuser.EmployeeID)
.

What are the changes to be done in code to add the user data to database through register page.

//For now I have done something like this: IN register.aspx page I changed this(in BOLD)

protected void CreateUser_Click(object sender, EventArgs e)
{
var manager = Context.GetOwinContext().GetUserManager<ApplicationUserManager>();
var user = new ApplicationUser() { UserName = Name.Text, Email = Email.Text , EmployeeID = EmployeeID};
IdentityResult result = manager.Create(user, Password.Text);

Hi harshilshah,

Thanks for your post.

Based on my understanding ,you want to add extra information in  AspNetUsers database table?

Firstly you need to install these two packages:- Microsoft.Aspnet.Identity.Core

This package contains the core interfaces of ASP.NET Identity.Microsoft.Aspnet.Identity.EntityFramework

This package contains the implementation of ASP.NET Identity System which works with Entity Framework Code First. This means that if we use this package then we can store information in a SQL Server database. Also we can easily plug other databases if we
wanted.and then updated your IDE

Secondly,Enable Entity Framework Code First Database Migrations.Thirdly,Add new properties

Fourthly,Add New Migration

Fifthly,Update RegisterViewModel

and then Update Register View Page and Update Account Controller’s Register action (Post Version)

Details information:

#Customize User’s Profile in ASP.NET Identity System

http://www.itorian.com/2013/11/customize-users-profile-in-aspnet.html

Hope this can be helpful.

Best Regards.

Eileen

[RESOLVED]Redirecting to different controller on button click

I am working on a very simple CRUD gui and I’m struggling with getting the redirect correct so that it will forward the user to another controller.  Currently it just does nothing.  Below is what i have.

Trying to redirect "Notes" to the NotesModel

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Data.Entity;
using Robinson_TestApp.Models; 

namespace Robinson_TestApp.Controllers
{
    public class ProductController : Controller
    {
        private DataTransportDataContext context;
        public ProductController()
        {
            context = new DataTransportDataContext();
        }

        public ActionResult Index()
        {
            IList<ProductModel> ProductList = new List<ProductModel>();
            var query = from Product in context.Products
                        select Product;

            var products = query.ToList();
            foreach (var ProductData in products)
            {
                ProductList.Add(new ProductModel()
                {
                    ID = ProductData.ID,
                    Name = ProductData.Name,
                });
            }
            return View(ProductList);
        }

        public ActionResult Create()
        {
            ProductModel model = new ProductModel();
            return View(model);
        }

        [HttpPost]
        public ActionResult Create(ProductModel model)
        {
            try
            {
                Product prod = new Product()
                {
                    Name = model.Name,
                };
                context.Products.InsertOnSubmit(prod);
                context.SubmitChanges();
                return RedirectToAction("Index");
            }
            catch
            {
                return View(model);
            }
        }

        public ActionResult Notes()
        {
            NotesModel model = new NotesModel();
            return RedirectToAction("Index", "NotesController");
        }

        [HttpPost]
        public ActionResult Notes(NotesModel model)
        {
            return RedirectToAction("Index", "NotesController");
        }

        protected override void Dispose(bool disposing)
        {
            context.Dispose();
            base.Dispose(disposing);
        }
    }
}

Here is the NotesController

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Robinson_TestApp.Models;

namespace Robinson_TestApp.Controllers
{
    public class NotesController : Controller
    {
        private DataTransportDataContext context;
        
        public NotesController()
        {
            context = new DataTransportDataContext();
        }

        private void CreateNotes(NotesModel model)
        {
            model.Notes = context.Products.AsQueryable<Product>().Select(x => 
                new SelectListItem()
            {
                Text = x.Name,
                Value = x.ID.ToString()
            });
        }

        public ActionResult Index()
        {
            IList<NotesModel> NoteList = new List<NotesModel>();
            var query = from note in context.ProductNotes
                        join product in context.ProductNotes
                        on note.ID equals product.ID
                        select new NotesModel
                        {
                            ID = note.ID,NoteText = note.NoteText, Date = note.CreateDate //Archived = note.Archived
                        };
            NoteList = query.ToList();
            return View(NoteList);
        }

        public ActionResult Details(int ID)
        {
            NotesModel model = context.ProductNotes.Where(x => x.ID == ID).Select(x =>
                                                    new NotesModel()
                                                    {
                                                        ID = x.ID,
                                                        NoteText = x.NoteText,
                                                        Date = x.CreateDate,
                                                        //Archived = x.Archived
                                                    }).SingleOrDefault();
            return View(model);
        }

        public ActionResult Create()
        {
            NotesModel notes = new NotesModel();
            CreateNotes(notes);
            return View(notes);
        }

        [HttpPost]
        public ActionResult Create(NotesModel model)
        {
            try
            {
                ProductModel prod = new ProductModel();
                DateTime date = new DateTime();
                ProductNote note = new ProductNote()                
                {
                    ID = prod.ID,
                    NoteText = model.NoteText,
                    CreateDate = date.Date
                };
                context.ProductNotes.InsertOnSubmit(note);
                context.SubmitChanges();
                return RedirectToAction("Index");
            }
            catch
            {
                return View(model);
            }
        }
        public ActionResult Edit(int id)
        {
            NotesModel notes = context.ProductNotes.Where(x => x.ID == id).Select(x =>
                                 new NotesModel()
                                 {
                                     ID = x.ID,
                                     NoteText = x.NoteText,
                                     Date = x.CreateDate,
                                 }).SingleOrDefault();

            CreateNotes(notes);
            return View(notes);
        }

        [HttpPost]
        public ActionResult Edit(NotesModel model)
        {
            try
            {
                ProductNote note = context.ProductNotes.Where(x => x.ID == model.ID).Single<ProductNote>();
                note.NoteText = model.NoteText;
                note.CreateDate = model.Date;
                context.SubmitChanges();
                return RedirectToAction("Index");
            }
            catch
            {
                return View(model);
            }
        }

        public ActionResult Delete(int id)
        {
            NotesModel model = context.ProductNotes.Where(x => x.ID == id).Select(x =>
                                   new NotesModel()
                                   {
                                       ID = x.ID,
                                       NoteText = x.NoteText,
                                       Date = x.CreateDate,
                                   }).SingleOrDefault();
            return View(model);
        }
        
        [HttpPost]
        public ActionResult Delete(NotesModel model)
        {
            try
            {
                ProductNote note = context.ProductNotes.Where(x => x.ID == model.ID).Single<ProductNote>();
                note.NoteText = model.NoteText;
                note.CreateDate = model.Date;
                context.SubmitChanges();
                note.Archived = true;
                return RedirectToAction("Index");
            }
            catch
            {
                return View(model);
            }
        }
    }
}

 

The easiest way is to use TempData to pass model to your Notes controller

        [HttpPost]
        public ActionResult Notes(NotesModel model)
        {
            TempData["Model"] = model;
            return RedirectToAction("Index", "Notes");
        }

Do I need to declare that TempDataDictionary in the Product Model?

public TempDataDictionary TempData { get; set; }

Hi,

No you don’t have to declare it in your model. The tempdata dictionary is just available , but its values only till the next request. Pls see:
http://msdn.microsoft.com/en-us/library/dd394711(v=vs.100).Aspx for further details.

Regards,

Yorrick

Thank you Yorrick, it doesnt appear this is the way I should be doing this.  I need this to work everytime, and currently as I have it written it isnt working at all.  It appears to be redirecting to the index of the controller its currently using vs to
the other controller….  Here is the product controller where I added the TempData function.  I’ve read the msdn link you posted and I’m not sure where I’ve gone wrong!

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Data.Entity;
using Robinson_TestApp.Models;
using Robinson_TestApp.Controllers; 

namespace Robinson_TestApp.Controllers
{
    public class ProductController : Controller
    {
        private DataTransportDataContext context;
        public ProductController()
        {
            context = new DataTransportDataContext();
        }

        public ActionResult Index()
        {
            IList<ProductModel> ProductList = new List<ProductModel>();
            var query = from Product in context.Products
                        select Product;

            var products = query.ToList();
            foreach (var ProductData in products)
            {
                ProductList.Add(new ProductModel()
                {
                    ID = ProductData.ID,
                    Name = ProductData.Name,
                });
            }
            return View(ProductList);
        }

        public ActionResult Create()
        {
            ProductModel model = new ProductModel();
            return View(model);
        }

        [HttpPost]
        public ActionResult Create(ProductModel model)
        {
            try
            {
                Product prod = new Product()
                {
                    Name = model.Name,
                };
                context.Products.InsertOnSubmit(prod);
                context.SubmitChanges();
                return RedirectToAction("Index");
            }
            catch
            {
                return View(model);
            }
        }

        public ActionResult Notes()
        {
            NotesModel model = new NotesModel();
            return RedirectToAction("Index", "NotesController");
        }

        [HttpPost]
        public ActionResult Notes(NotesModel model)
        {
            TempData["Notes"] = model;
            return RedirectToAction("Index", "Notes");
        }

        protected override void Dispose(bool disposing)
        {
            context.Dispose();
            base.Dispose(disposing);
        }
    }
}

Hi th3knick,

Thanks for your post.

th3knick

Do I need to declare that TempDataDictionary in the Product Model?

You didn’t need to declare TempDataDictionary,it’s a property under ControllerBase Class.

Please check this:http://msdn.microsoft.com/en-us/library/system.web.mvc.controllerbase(v=vs.118).aspx

More information about TempData,you can check this:

#What is ViewData, ViewBag and TempData? – MVC options for passing data between current and subsequent request

http://www.codeproject.com/Articles/476967/WhatplusisplusViewData-cplusViewBagplusandplusTem

Hope this can be helpful.

Best Regards,

Eileen

Hi,

Why it isn’t redirecting to your "Notes" Controller, assuming that the controller exist and the name is spelled correctly, I can’t say. Your code sample should work. But What I don’t understand in your code below is why this solution:

        [HttpPost]
        public ActionResult Notes(NotesModel model)
        {
            TempData["Notes"] = model;
            return RedirectToAction("Index", "Notes");
        }

It seems that you post to this method from your view and after that use "TempData" and "RedirectToAction" to transport the model to the "Index" method of the "Notes" Controller. This doesn’t seem to be very economical. Why do you do this this way? Why not
posting directly to the “Notes” controller from the view? That way you only have to do one request instead of two.

Another thing that could be refactored into something more economical ;-) is the following:

public ActionResult Index()
        {
            IList<ProductModel> ProductList = new List<ProductModel>();
            var query = from Product in context.Products
                        select Product;

            var products = query.ToList();
            foreach (var ProductData in products)
            {
                ProductList.Add(new ProductModel()
                {
                    ID = ProductData.ID,
                    Name = ProductData.Name,
                });
            }
            return View(ProductList);
        }

into:

public ActionResult Index()
{
	var productList = (from product in context.Products 
			   select new ProductModel
			   {
				ID = product.ID,
			        Name = product.Name										
			    }).ToList();
	return View(productList);
}

Hope this helps.

Regards,

Yorrick

[RESOLVED]Bind IDictionary List to MVC WebGrid

I’m dont know how to bind an IDictionary list to a MVC WebGrid. This is what I have so far

 public List<IDictionary> GetAddress()
        {
            List<IDictionary> names = new List<IDictionary>();
        //List<string> names = new List<string>();
            using (MVCDBEntities example = new MVCDBEntities())
            {
                var Uus = from U1 in example.Users where U1.Name != null select U1;
                names = Uus.OfType<IDictionary>().ToList();
            }
            return names;
        }

I now need to some how bind  this to a webgrid, how would I achieve this ?

Hi,

taken from

http://forums.asp.net/t/1719060.aspx?Binding+MVC3+webgrid+from+DataTable+AsEnumerable+:

Model method:

public List<IDictionary> FetchEmployeeDetails()
         {
             DataSet dsEmployee = new DataSet();
             DbCommand dbCmd = m_DbAccess.SqlDb.GetStoredProcCommand("Test_FetchEmployeeDetails");
             dbCmd.CommandType = CommandType.StoredProcedure;
             dsEmployee = m_DbAccess.SqlDb.ExecuteDataSet(dbCmd);

             return ConvertToListDictionary(dsEmployee.Tables[0]);
         }

Controller Code:

public ActionResult FetchDataForGrid()
         {
             EmployeeModels modelObject = new EmployeeModels();
             var resultSet = modelObject.FetchEmployeeDetails();
             return View(resultSet);
        }

View Code:

@using System.Dynamic
 @model List<System.Collections.IDictionary>
 @{
     var result = new List<dynamic>();

     foreach (var emprow in Model)
     {
         var row = (IDictionary<string, object>)new ExpandoObject();
         Dictionary<string, object> eachEmpRow = (Dictionary<string, object>)emprow;

         foreach (KeyValuePair<string, object> keyValuePair in eachEmpRow)
         {
             row.Add(keyValuePair);
         }
         result.Add(row);
     }
     var grid = new WebGrid(result);
 }

 @if (@Model != null)
 {
     @grid.GetHtml(tableStyle: "grid", headerStyle: "head", alternatingRowStyle: "alt");
 }

Grz, Kris.

Thanks for the reply, I am just getting an error with the IDictionary list anyways thanks for your time.  Is there anyway you can just use a asp.net Gridview control with something like this with the entity framework ? As binding data to a webgrid in mvc
is a joke, so much extra work, in php its easier than this

Hi,

you can’t really make use of the gridview in MVC.

What you can do, and what I did in the past, is make use of jqGrid and bind the grid client side. There are also commercial tools for this like KendoUI and others.

Grz, Kris.

How to iterate model and save to database?

How can you iterate through a single model and save it multiple times so that a new record/row is created in the database?

For example I have an application form and I wish to create multiple applications using the same details but for each application I will change the applicant.

I have the following controller action to which attempts to achieve this:

public ActionResult Create([Bind(Prefix = "Application")]Application application, FormCollection collection)
{

List<string> selectedEmployees = new List<string>();

// Application.EmpIDs is a multiselect drop down list
if (collection["Application.EmpIDs"] == null)
{
	ModelState.AddModelError("Employee", "Please select an employee");
}
else
{
	selectedEmployees.AddRange(collection["Application.EmpIDs"].Split(',').ToList());
}



if (ModelState.IsValid)
{

   
   foreach (var item in selectedEmployees)
   {
	// Add emp id
	application.EmpID = Convert.ToInt32(item);
                           
                            
	// Add Application
	_repository.AddApplication(application);

	// Persist changes back to database
	_repository.Save();

	

    }
}

//...more stuff

}

however i end up with the following error message:

An object with the same key already exists in the ObjectStateManager. The existing object is in the Modified state. An object can only be added to the ObjectStateManager again if it is in the added state.

It sounds like the object you are looking for already exists within your context. Have you tried removing the AddApplication() call and just calling the Save() (or SaveChanges()) method on it’s own? If Entity Framework is tracking your elements,
then it will track changes (such as new or updated property values) which will be saved to the database when the Save method is called :

// Add emp id
application.EmpID = Convert.ToInt32(item);
                           
// Persist changes back to database
_repository.Save();

You might also want to consider taking a look at the data within your database to be sure that you don’t have any issues or duplicate keys (or any logical issues that could cause that to occur).

the AddApplication() call simply updates some additional property values. The full method is below:

public void AddApplication(Application application)
{
            application.StatusID = 1;
            application.CreatedDate = DateTime.Now;
            application.LastModifiedDate = DateTime.Now;
            application.StatusDate = DateTime.Now;

            _entities.Applications.AddObject(application);

}

there should be no issues with the database becuase each application has an autoincrement primary key.

ok i’ve managed to get this working by adding the following line after the save method:

// Detach the entity from object context
_repository.Detach(application);

However I need get the ids of all the newly added applications. I have added the following list below the save method but all i get added into this list is the first application multiple times hence i end up with the same application id.

// Persist changes back to database
_repository.Save();

// create list of applications added to reference new application ids
// this is basically a list  List<Application> applicationsSubmitted = new List<Application>();
applicationsSubmitted.Add(application);
// Detach the entity from object context 
_repository.Detach(application);

[RESOLVED]Re-using the same model, same controller with different views

I didn’t think that this was going to cause me so much difficulty .. and I have only just started with this project Surprised

I have one model which I want to populate the model’s properties over multiple views. I was planning on using the controller to determine which View should be displayed.

The model looks like this:

public class QC_Rework
{
    public int nViewToDisplay { get; set; }
    public int nReworkNumber { get; set; }
    public string cSecondaryReferenceType { get; set; }
    public string cSecondaryReferenceNumber { get; set; }
    public int nLineQuantity { get; set; }
}

My "Create" controller looks like this:

[HttpGet]
public ActionResult Create([Bind(Prefix = "ReworkNumber")] int ReworkNumber=0)
{

    var oQC = new QC_Rework();
    oQC.nReworkNumber = ReworkNumber;
    oQC.nViewToDisplay = 1;
    return View("GetSecondaryReferenceType2", oQC);

}

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(QC_Rework oQC_Rework)
{
    // After GetSecondaryReferenceNumber2 the value of nViewToDisplay is "1"!!!
    // Even though the value in the Source Code and in the form says "2"!!!
    if (ModelState.IsValid)
    {
        switch (oQC_Rework.nViewToDisplay)
        {
            // Coming from Secondary Reference Type View
            case 1:
                if (String.IsNullOrEmpty(oQC_Rework.cSecondaryReferenceType) == true)
                {
                    ModelState.AddModelError("Model", "A secondary reference type needs to be selected!");
                    return View("GetSecondaryReferenceType2", oQC_Rework);
                }
                else
                {
                    oQC_Rework.nViewToDisplay = 2;
                    return View("GetSecondaryReferenceNumber2", oQC_Rework);

                }
            // Coming from Secondary Reference Type View
            case 2:
                {
                    oQC_Rework.nViewToDisplay = 3;
                    return View("GetQCDetails2", oQC_Rework);
                }
        }
    }
    // Should not get here at this stage!
    return View("NotFound", oQC_Rework);
}

The model’sproperty nViewToDisplay controls which Views get displayed.

When I debug the code, before the View GetSecondaryReferenceNumber2 gets called, the value in oQC_Rework.nViewToDisplay is set to 2 … but in the view itself it is "1′!!

What am I doing wrong?

Many thanks …

you don’t show the view code, but most likely its something like:

   @Html.HiddenFor(m=>m.nViewToDisplay)

with the html helpers, the lambda expression is just to get the name. ("nViewToDisplay") in your case. this name is then used to lookup the value. The postback form collection is searched before the ViewBag.Model (where you changed the data). so the postback
value is used.

just use a vanilla hidden field:

  <input type="hidden" name="nViewToDisplay" value="@Model.ViewBag.nViewToDisplay" />

or original helper that takes the value

   @Html.Hidden("nViewToDisplay",ViewBag.nViewToDisplay)