Tag Archives: HTML

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

How can I use async in Application_Error() in Global.asax.cs?

I’m not sure if I’m doing everything correctly, but what I want to do is basically log my errors to an external service. The problem is that I’d like to use async/await, but if I add async to the Application_Error, it doesn’t seem to get called.

Maybe that is not modified . Use .Result for task – or, if you want  all to finish, Task.WaitAll

jakubarnold

I’m not sure if I’m doing everything correctly, but what I want to do is basically log my errors to an external service. The problem is that I’d like to use async/await, but if I add async to the Application_Error, it doesn’t seem to get called.

Hi jakubarnold,

Thanks for your post.

What I understand from you is that you want to write mvc application exception message to remote server asynchronously.

For this issue, you should mark the Application_Error as async like below:

protected async void Application_Error(object sender, EventArgs e) 
        {
            Exception ex = Server.GetLastError();
            var isSuccess=await MethodAsync(ex);
        
        }
async Task<bool> MethodAsync(Exception ex)
        {
            //your code write exception to remote server.
            //...............

            return true;
        }

Thanks.

Best Regards!

The HTTP pipeline has APIs to register for async versions of all the methods you see in global.asax. You can then incorporate that with Tasks. This might help:

http://brockallen.com/2013/07/27/implementing-async-http-modules-in-asp-net-using-tpls-task-api/

Is your intention is to return the page back to the user while logging the error? Typically this makes sense as you don’t want to block user while logging errors. Async does not support this behavior. It will still be a synchronous call to your user. Please
check the below blog for more details

Async Doesn’t Change the HTTP Protocol

If your intension is not to hold up the web server thread while doing the error logging, I recommend using async HttpModules for this.

Implementing async HTTP modules in ASP.NET using TPL’s Task API

[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]edit.cshtml(scaffold), validate database field to accept only 3 value

Hi!

In edit.cshtml(scaffold) I have field1(from database):

<div
class="editor-field">

            @Html.EditorFor(model => model.field1)

            @Html.ValidationMessageFor(model => model.field1)   

</div>

       

    How can I   validate field1(string type)

     to accept only 3  value  ( ex: value1, value2, value3) ?

  Thanks!

Did you meant that comma separted value in a text box?

Hi fvi,

For this requirement, you could use RegularExpressionAttribute class or custom validation.

More information, please refer to:

# RegularExpressionAttribute Class

http://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.regularexpressionattribute(v=vs.110).aspx

# Custom Unobtrusive jQuery Validation with Data Annotations

http://thewayofcode.wordpress.com/2012/01/18/custom-unobtrusive-jquery-validation-with-data-annotations-in-mvc-3/

Best Regards

Starain Chen

[RESOLVED]page and ajax

When the page
shows a portion of the content
using
ajax, it
has 2
connection -
to the current page
and the page
requested by ajax?
Likewise with the
iframe? Trying to
optimize your site, but it turns out
that the use of Ajax
only
clog the channel.

It initiates a new connection, but these connections are permanent, they only exist until the content is retrieved.  Use the network section of the browser’s developer tools (f12) and you’ll get to see all the connections your page makes.  It will make a
connection for each image, script file, css file etc too.  If any ajax code runs that will instantiate a connection, as will an Iframe, and any resources (images, script files, css files) used in the iframe will kick off a connection, as will any images etc
referenced by html you return from your ajax call.

[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]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.

[RESOLVED]how can i use url.action in @helper method ?

Hi dear ,

 I create a @helper method and use @Url.Action helper in it.(in App_Code Folder)

@helper GetNews(int CategoryID, int Rows)
{
         <div class="@Style" id="@CategoryID">
         
                  <a style="padding-right:10px" href="@Url.Action("Rss", "Home", new { type="News" , cid = CategoryID})"><img src="@Url.Content("~/images/icon/rss.png")" /></a>
                                &nbsp;
                                <a href="@Url.Action("Details", "News", new { cid=CategoryID,sid=Model})">arshive</a>
                             </div>
                        
}

after run i get an error :

Compilation Error 
  Description: An error occurred during the compilation of a resource required to service this request. Please review the following specific error details and modify your source code appropriately. 

 Compiler Error Message: CS0103: The name 'Url' does not exist in the current context

Source Error:


 

Line 193:                                </table>*@
Line 194:
Line 195:                                <a style="padding-right:10px" href="@Url.Action("Rss", "Home", new { type="News" , cid = CategoryID})"><img src="@Url.Content("~/images/icon/rss.png")" /></a>
Line 196:                                &nbsp;
Line 197:                                <a href="@Url.Action("Details", "News", new { cid=CategoryID,sid=Model})">arshive</a>
 

Also,
I had
to have
a class named ExtensionMethodHelper
for create external helpers and use it ( in Model folder ).but i
can not call
this
external helpers on the page(.cshtml) that
I’ve created
in
App_Code folder.

in fact after write @Html.  i dont find my favorite external helper (in ExtensionMethod class in Model folder).

for e.g : Html.PersianDate made in ExtensionMethodHelper in Model Folder

   <span class="date">@Html.ToPersianDate(item.DateToShow)</span>

in :

below helper create in App_Code

@helper GetNews(int CategoryID, int Rows)
{
       <div class="@Style" id="@CategoryID">
                <a style="padding-right:10px" href="@Url.Action("Rss", "Home", new { type="News" , cid = CategoryID})"><img src="@Url.Content("~/images/icon/rss.png")" /></a>
                       &nbsp;
                   <a href="@Url.Action("Details", "News", new { cid=CategoryID,sid=Model})">arshive</a>
       </div>
                        
}

 how can i solve it

please help me

thanks

I use the "UrlHelper" class to do this.  Here’s a helper I always used in my projects (prior to bundles).  Use it as an example to expand on your own:

// file name is "Content.cs" stored in App_Code folder

@using System.Web.Mvc; @helper Script(string scriptName, UrlHelper url) { <script type="text/javascript" src="@url.Content("~/Scripts/" + scriptName)"></script> }

the helper in my View then looks like:

@Content.Script("jquery-1.10.1.min.js", Url)

You can see that I pass the "Url" to the helper.  Your helper would then look like…

@helper GetNews(int CategoryID, int Rows, UrlHelper url)
{
  ...

  <a href="@url.Action("Rss", "Home", ...)">

  ...
}

the "url" is lowercase fyi.  Don’t confuse it with Url