[RESOLVED]How to resize image when upload and make bigger the time allow to run scripts

Hi, i got 2 problems

First problem, when users try to upload photos bigger than 1,5 MB i would love to resize the photo to be max 1,5 MB, how to do?

this is the code i use to upload a picture :

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);
                            

                            creation.CreationPhotoBis = fileName; 

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



                        }


                        }
                    }

Second problem, if this upload action tak more the certain time i got a message that i go over my allowed tim for script, how to avoid it? or make this time bigger when upload?

Somebody can help me to implement this code?

Thanks

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

How to solve Error : Could not copy … Exceeded retry count of 10. Failed.

hi

i have a MVC web application. its name is StartWPTFramework.

when i run my program it runs iis express and show my website correctly.

when i stop application , iis express and my application remains running. now if i change a little any part of any project in solution and run my program again this error will appear for projects that have been changed.

Could not copy "objDebugStartWPTFramework.dll" to "binStartWPTFramework.dll". Exceeded retry count of 10. Failed.
Could not copy "D:MyFIlesPROWPT.MVC.CMSWPTWPTFrameworkCorebinDebugWPTFrameworkCore.dll" to "binWPTFrameworkCore.dll"

is there any one knows the problem?

You’ll likely want to ensure that your application has stopped running completely. 

You can do this by checking either the Task Manager and looking for any processes related to IIS or your application and stop them prior to editing your application :

This could also be a permissions issues as well. You could try running Visual Studio as an Administrator (Right-click > Run as Administrator) to see if that helps. Additionally, a few users have mentioned this issue as a possible bug within Visual
Studio as seen in this related thread, which might be worth looking through as well.

as i said the IIS and my application in IIS Remain open after stop debugging.

i tried running VS as administrator but problem not solved.

Hi morteza,

After change a project, please clean and rebuild your solution.

On the other hand, please create a new solution with some projects and try again to check the result.

If you still have the issue, please share it to us (OneDrive).

Thanks

Best Regards

i cleaned and rebuilt it but problem not solved.

is there any way to close iis express automatically when i stop debugging? i tried disabling "Enable edit and Continue" but iis express still running after stop debugging.

Hi morteza,

As far as I know the IIS Express won’t stop automatically unless it crash. Also stop debugging the project won’t stop IIS.

Please try to stop the IIS Express manually, then rebuild your project and try again.

Right click IIS Express icon (Notification Area) in the taskbar and click exit.

Thanks

Best Regards

i know how manually stop iis. and as i said before if i stop it the problem will solve. but im looking for a way to stop it automatically.

i think the problem is that after running web application iis load dlls of my project directly from bin folder.

i used this tag in web.config of startProject:

<hostingEnvironment shadowCopyBinAssemblies="true" />

but dlls of dependent projects still load from bin folder.

Could you resolve this issue by change the tag to false? Thank you. 

I tested that if you click stop debugging from the Visual studio. The IISexpress will exit automatically.

Hi Morteza,

It seems there some cross referencing has been done. 

Delete the bin and obj folder. Rebuild the solution again. This will probably solve your issue.

Regards

Pawan

none of this solved my problem.

in my application i load some dlls with Assembly.Load from bin folder.

i think that if i load my dlls from temp asp folder my problem will solve.

is there any way to find the path of dll of specific project in asp temp folder?

Hi,

Pls delete the bin folder and rebuilt the application

[RESOLVED]How to chek why my website is long to be downloaded and what to do to decrease this time

Hi, i notice that my web site takes more time to be downloaded if i compare with other sites with same amounth of images…

How can i find what make my site long to be downloaded?

And how to fix?

Thanks

I believe the issue here is likely related to the physical sizes of your images, which can take quite some time to download if they are extremely large.

You’ll want to ensure that the image matches the size of the container you are intending to place it in and that the image has been optimized (to help reduce the size of it). When you see this occurring on a site, it is typically because the image
that is being loaded is :

  • The image(s) may be too large (for example a 800×800 image being loaded into a 100×100 container requires the browser to do lots of unnecessary work)
  • The image(s) are not optimized (you can use several online compressors like Smush.It or Kraken.io to optimize your images online)
  • The image(s) are physically quite large (this can depend on the types of files being uploaded, as files like bitmaps are extremely large).

Optimizing your images will likely help this issue tremendously. If you want to look at these requests, consider using the Developer Tools (F12) within Chrome and checking out the Network tab which will allow you to see each of your AJAX requests that are
made and their sizes.

Consider Using a Third-Party Analyzer

I would recommend running something an analyzer like one of the following on your site :

  • Using Google PageInsights - Google’s PageInsights can help you find areas of improvement and offers suggestions on how to get your site running faster.
  • Using Yahoo’s YSlow Analyzer - Very similar to Google’s PageInsights, YSlow looks for areas that you can check to improve the performance of your site.

It will provide you with any major concerns that might be slowing down performance on your site and how to resolve these issues. You might see something like the following after running it, which will let you know what images you need to consider optimizing
and the amount of size that you will save :

One Final Recommendation

If you want an excellent resource that encompasses a variety of methods to improve your website or web application, I cannot recommend the Web Developer Checklist enough. There
is also an ASP.NET-specific version available on the site as well
 and one that focuses specifically on ASP.NET Performance. It’s probably one of the best single resources that I have found for
improving nearly all aspects of a website or web application.

[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