Category Archives: Post

Post

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]LINQ to Entities, selecting mutiple columns to already declared model getting anonymous type error.

I am trying to fill my `ViewModel` from a few different LINQ queries but I am running into the problem of trying to fill multiple properties from a single LINQ query but I get the error

"invalid anonymous type member declarator. anonymous type members must be declared with a member assignment, simple name or member access"

I have done some searches and founds some posts but they are all about completely filling a `ViewModel` and not just a few properties like I am trying to do. What am I supposed to do to fix this, or am I going about this completely wrong?

using (ForumContext db = new ForumContext())
{
	model.ID = db.yaf_Topic
				.Where(t => t.ForumID == 5)
				.OrderByDescending(t => t.Posted)
				.Select(t => t.PollID.Value).First();

	model = db.yaf_Poll
				.Where(p => p.PollID == model.ID)
				.Select(p => new
				{
					model.Question = p.Question,
					model.IsMultipleChocie = p.AllowMultipleChoices,
					model.ExperationDate = p.Closes
				})
				.First();

	model.Choices = db.yaf_Choice
						.Where(c => c.PollID == model.ID)
						.Select(c => new
						{
							model.Votes.Key = c.Choice,
							model.Votes.Value = c.Votes,
						})
						.ToList();

	model.VotedIPs = db.yaf_PollVote
						.Where(p => p.PollID == model.ID)
						.Select(p => p.RemoteIP)
						.ToList();

	model.VotedUserIDs = db.yaf_PollVote
							.Where(p => p.PollID == model.ID)
							.Select(p => p.UserID)
							.ToList();
}

ViewModel:

public class PollVM
{
	public int ID { get; set; }
	public string Question { get; set; }
	public bool IsMultipleChocie { get; set; }
	public DateTime? ExperationDate { get; set; }
	public KeyValuePair<string, int> Choices { get; set; }
	public List<string> VotedIPs { get; set; }
	public List<int?> VotedUserIDs { get; set; }
}

Here are the issues, I observe in your code

Eagle_f90

.Select(c => new

You are using anonymous type and hence you are getting the error, you need to specify the datatype as below

	model.Choices = db.yaf_Choice
						.Where(c => c.PollID == model.ID)
						.Select new KeyValuePair<string, int>(c.Choice, c.Votes)
						})
						.ToList();

You should make your Choices to be a list of keyvaluepair

public List<KeyValuePair<string, int>> Choices { get; set; }


Eagle_f90

model = db.yaf_Poll		
.Where(p => p.PollID == model.ID) .Select(p => new { model.Question = p.Question, model.IsMultipleChocie = p.AllowMultipleChoices, model.ExperationDate = p.Closes }) .First();

With this step you are overriding your previous step of setting Model.ID. Also you need to change the "new" to something like I mentioned above.

[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]Seting property value causes tack Overflow state error.

I think I am over looking something extremely simple on this one but just can’t put my finger on it. I am trying to set the value of a public property in my ViewModel but when I do it errors out with "Cannot evaluate expression because the current thread
is in a stack overflow state". What am I missing?

public class PollVM
{
	public PollVM()
	{
		this.Choices = new List<KeyValuePair<string, int>>();
	}

	public int ID { get; set; }
	public string Question { get; set; }
	public bool IsMultipleChocie { get; set; }
	public DateTime? ExperationDate { get; set; }
	public List<KeyValuePair<string, int>> Choices { get; set; }
	public List<string> VotedIPs { get; set; }
	public List<int?> VotedUserIDs { get; set; }
	public bool HasVoted { get; set; }

	public string Title
	{
		get
		{
			return Title.Replace(" ", "-");
		}

		set
		{
			Title = value;
		}
	}
}

Eagle_f90

public string Title
	{
		get
		{
			return Title.Replace(" ", "-");
		}

		set
		{
			Title = value;
		}
	}

When you assign a value to the Title property, your set code is then also assigning the value to the Title property, which calls the set code again which is then also assigning … – hence the stack overflow.

You need to either add a backing variable manually to store that value behind the property (i.e. a private string _title;  ) and then your set code would be _title = value;

for example:

private string _title;
public string Title
	{
		get
		{
			return _title.Replace(" ", "-");
		}

		set
		{
			_title = value;
		}
	}

Or you should leave the setter code empty to allow the compiler add the backing variable for you

i.e

set;

mbanavige

Or you should leave the setter code empty to allow the compiler add the backing variable for you

i.e

set;

When I change it to

public string Title
{
	get
	{
		return Title.Replace(" ", "-");
	}

	set;
}

I get the error "PollVM.Title.set’ must declare a body because it is not marked abstract, extern, or partial"

since you are manipulating the value returned by the get, i’d just go with the explicit backing variable.

sample of that also posted above.

[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]Order of an image

Hi, in my database i create a table where i held the infos of my pictures… and also the order in number format…

After i order them by my order field.. till here all ok…

the problem is that at the moment i need to fill my order field with a number, but what i would love to do is the following :

In my list of pictures i would love to show 2 link : UP and DOW

If i click on up i would love to give to that picture the order of the upper picture and the upper picture to take the other order, in this way i can put up my picture…

So if i have :

1 –> AAAA (Up / Down)

2–> BBBB (Up / Down)

3–> CCCC (Up / Down)

4–> DDDD (Up / Down)

If i click on UP for the picture CCCC i should have :

1 –> AAAA (Up / Down)

2–> CCCC (Up / Down)

3–> BBBB (Up / Down)

4–> DDDD (Up / Down)

The problem is also for the first and the last picture, that they :

can’t go up for the first

can’t go down for the last

I hope i well explain what i would love to do…

How to do?

Hi grafic,

For this requirement, please follow up these steps below:

  1. Create an action method to update the order number.
    public ActionResult Index(int id, bool isUp)
    {
       //TODO retrieve current entity
       //TODO Validate order number (first, last)
       //Base on the order number retrieve privious/next entity
       //TODO 
    }
  2. Base on the order number to get the previous or next record. (Using ElementAt method)
  3. Update current entity with previous/next record order number and update previous entity with current entity’s order number.

For the first entity, you just need to check the order number. If the value of order number is 1, then it means that record is the first one.

For the last entity, you need to check all record count, if the order number equals to all record count, it means that record is the last one.

Best Regards

Starain Chen

Hi, sorry to bother.. can i have i bit more of code… because i never done this…

Thanks

Hi grafic,

Since I don’t have your project, I think you need to do it by yourself.

If you have any questions about these steps, you could post it here.

Best Regards

Starain Chen

[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