c#,asp.net-mvc,asp.net-mvc-5 , Submitting the form always calls get action method instead of post action method


Submitting the form always calls get action method instead of post action method

Question:

Tag: c#,asp.net-mvc,asp.net-mvc-5

Hi I've got the following code in my controller (asp.net 4.5.1 mvc 5) that allows a user to register on my site. Everything was working fine but Ive added another controller and another service and now when ever I try to register all it does on submit is redirect back to the form blank again. After debugging, the post action method in controller below is never called

[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Register(RegisterViewModel model)
{
    if (ModelState.IsValid)
    {
        var user = new ApplicationUser { UserName = model.Email, Email = model.Email };
        var result = await UserManager.CreateAsync(user, model.Password);
        if (result.Succeeded)
        {
            UserManager.AddClaim(user.Id, new Claim(ClaimTypes.GivenName, model.FirstName));
            var service = new GRCMemberService(HttpContext.GetOwinContext().Get<ApplicationDbContext>());
            service.CreateGRCMember(model.FirstName, model.LastName, model.Address1, model.Address2, model.City, model.County, model.Postcode, model.Telephone, model.DateOfBirth, model.Dietary, model.CompLicenceNo, model.SelectedLicenceTypeId, model.NOKFirstName, model.NOKLastName, model.NOKTelephone, model.RelationshipTypeId, model.OtherOrgsGRC, model.OtherClubEvents, model.OtherOrgsOutside, user.Id);
            //var currentUser = UserManager.FindByName(user.Id);
            //var newrole = ("GRCMember");
            //var roleresult = UserManager.AddToRole(currentUser.Id, newrole);
            await SignInManager.SignInAsync(user, isPersistent:false, rememberBrowser:false);

            // For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771
            // Send an email with this link
            // string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);
            // var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
            // await UserManager.SendEmailAsync(user.Id, "Confirm your account", "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>");

            return RedirectToAction("Index", "Home");
        }  
        AddErrors(result);
    }
    // If we got this far, something failed, redisplay form 
    return View(model); 
}

instead, the get action method below is always called every time I submit the form:

[AllowAnonymous]
public ActionResult Register()
{
    return View();
}

Any idea what's wrong?

Below is my ViewModel and View code.

ViewModel

public class RegisterViewModel
{
    [Required]
    [Display(Name = "First Name")]
    [StringLength(160, ErrorMessage = "First Name cannot be longer than 160 characters.")]
    public string FirstName { get; set; }

    [Required]
    [Display(Name = "Last Name")]
    [StringLength(160, ErrorMessage = "Last Name cannot be longer than 160 characters.")]
    public string LastName { get; set; }

    [Required]
    [Display(Name = "Address 1")]
    [StringLength(160, ErrorMessage = "Address1 cannot be longer than 160 characters.")]
    public string Address1 { get; set; }

    [Display(Name = "Address 2")]
    [StringLength(160, ErrorMessage = "Address2 cannot be longer than 160 characters.")]
    public string Address2 { get; set; }

    [Required]
    [Display(Name = "City")]
    [StringLength(100, ErrorMessage = "City cannot be longer than 100 characters.")]
    public string City { get; set; }

    [Display(Name = "County")]
    [StringLength(100, ErrorMessage = "County cannot be longer than 100 characters.")]
    public string County { get; set; }

    [Required]
    [Display(Name = "PostCode")]
    [StringLength(10, ErrorMessage = "Postcode cannot be longer than 10 characters.")]
    public string Postcode { get; set; }

    [Required]
    [Display(Name = "Telephone")]
    [StringLength(20, ErrorMessage = "Telephone cannot be longer than 20 characters.")]
    public string Telephone { get; set; }

    [StringLength(20, ErrorMessage = "Competition Licence Number cannot be longer than 20 characters.")]
    [Display(Name = "Licence Number")]
    public string CompLicenceNo { get; set; }

    [Display(Name = "Licence Type")]
    public int? SelectedLicenceTypeId { get; set; }

    [StringLength(200, ErrorMessage = "Competition Licence Number cannot be longer than 20 characters.")]
    [Display(Name = "Dietary Requirements - For events")]
    public string Dietary { get; set; }

    [Required]
    [StringLength(100, ErrorMessage = "Next of Kin Name cannot be longer than 100 characters.")]
    [Display(Name = "Next of kin First Name")]
    public string NOKFirstName { get; set; }

    [Required]
    [StringLength(100, ErrorMessage = "Next of Kin Name cannot be longer than 100 characters.")]
    [Display(Name = "Next of kin Last Name")]
    public string NOKLastName { get; set; }

    [Required]
    [StringLength(20, ErrorMessage = "Next of Kin Telephone cannot be longer than 20 characters.")]
    [Display(Name = "Next of kin Telephone")]
    public string NOKTelephone { get; set; }

    [Display(Name = "Next of kin Relationship")]
    public int? RelationshipTypeId { get; set; }

    [Required]
    [Display(Name = "Date of Birth")]
    [DataType(DataType.Date)]
    [DisplayFormat(DataFormatString = "{0:dd/mm/yyyy}", ApplyFormatInEditMode = true)]
    public DateTime DateOfBirth { get; set; }

    [Display(Name = "Allow other organisations on Grass Roots Clicks to contact you?")]
    public bool OtherOrgsGRC { get; set; }

    [Display(Name = "Allow other clubs you are a member of or ones whose events you enter to contact you?")]
    public bool OtherClubEvents { get; set; }

    [Display(Name = "Allow other organisations outside of Grass Roots Clicks that we are working with to contact you?")]
    public bool OtherOrgsOutside { get; set; }

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

    [EmailAddress]
    [Display(Name = "Confirm email")]
    [Compare("Email", ErrorMessage = "Your email and confirmation email do not match.")]
    public string ConfirmEmail { get; set; }

    [Required]
    [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
    [DataType(DataType.Password)]
    [Display(Name = "Password")]
    public string Password { get; set; }

    [DataType(DataType.Password)]
    [Display(Name = "Confirm password")]
    [Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
    public string ConfirmPassword { get; set; }
}

View

@model GRCWebApp.Models.RegisterViewModel

@{
    ViewBag.Title = "Register";
}

<h2 class="text-success">@ViewBag.Title</h2>
<div class="row">
    <div class="col-md-7">
        <div class="well bs-component">
            <form class="form-horizontal">
                <fieldset>
                    <section id="loginForm">
                        @using (Html.BeginForm("Register", "Account", FormMethod.Post, new { @class = "form-horizontal", role = "form" }))
                        {
                            @Html.AntiForgeryToken()
                            <hr />
                            @Html.ValidationSummary("", new { @class = "text-danger" })

                            <h3 class="text-success col-md-offset-1">Name &amp; Address</h3>
                            <div class="form-group">
                                <div class="row">
                                    <div class="col-md-3  col-md-offset-1">
                                        @Html.LabelFor(model => model.FirstName, htmlAttributes: new { @class = "control-label" })
                                        @Html.EditorFor(model => model.FirstName, new { htmlAttributes = new { @class = "form-control", placeholder = "John" } })
                                        @Html.ValidationMessageFor(model => model.FirstName, "", new { @class = "text-danger" })
                                    </div>
                                    <div class="col-md-4 col-md-offset-2">
                                        @Html.LabelFor(model => model.LastName, htmlAttributes: new { @class = "control-label" })
                                        @Html.EditorFor(model => model.LastName, new { htmlAttributes = new { @class = "form-control", placeholder = "Smith" } })
                                        @Html.ValidationMessageFor(model => model.LastName, "", new { @class = "text-danger" })
                                    </div>
                                </div>
                                <div class="row">
                                    <div class="col-md-5 col-md-offset-1">
                                        @Html.LabelFor(model => model.Address1, htmlAttributes: new { @class = "control-label" })
                                        @Html.EditorFor(model => model.Address1, new { htmlAttributes = new { @class = "form-control", placeholder = "1 Apple Road" } })
                                        @Html.ValidationMessageFor(model => model.Address1, "", new { @class = "text-danger" })
                                    </div>
                                    <div class="col-md-5">
                                        @Html.LabelFor(model => model.Address2, htmlAttributes: new { @class = "control-label" })
                                        @Html.EditorFor(model => model.Address2, new { htmlAttributes = new { @class = "form-control", placeholder = "Neighbourhood" } })
                                        @Html.ValidationMessageFor(model => model.Address2, "", new { @class = "text-danger" })
                                    </div>
                                </div>

                                <div class="row">
                                    <div class="col-md-5 col-md-offset-1">
                                        @Html.LabelFor(model => model.City, htmlAttributes: new { @class = "control-label" })
                                        @Html.EditorFor(model => model.City, new { htmlAttributes = new { @class = "form-control", placeholder = "Some Town" } })
                                        @Html.ValidationMessageFor(model => model.City, "", new { @class = "text-danger" })
                                    </div>
                                    <div class="col-md-5">
                                        @Html.LabelFor(model => model.County, htmlAttributes: new { @class = "control-label" })
                                        @Html.EditorFor(model => model.County, new { htmlAttributes = new { @class = "form-control", placeholder = "Someshire" } })
                                        @Html.ValidationMessageFor(model => model.County, "", new { @class = "text-danger" })
                                    </div>
                                </div>
                                <div class="row">
                                    <div class="col-md-3 col-md-offset-1">
                                        @Html.LabelFor(model => model.Postcode, htmlAttributes: new { @class = "control-label" })
                                        @Html.EditorFor(model => model.Postcode, new { htmlAttributes = new { @class = "form-control", placeholder = "AA1 2BB" } })
                                        @Html.ValidationMessageFor(model => model.Postcode, "", new { @class = "text-danger" })
                                    </div>
                                </div>
                            </div>
                            <h3 class="text-success col-md-offset-1">Contact Details</h3>
                            <div class="form-group">
                                <div class="row">
                                    <div class="col-md-4 col-md-offset-1">
                                        @Html.LabelFor(model => model.Telephone, htmlAttributes: new { @class = "control-label" })
                                        @Html.EditorFor(model => model.Telephone, new { htmlAttributes = new { @class = "form-control", placeholder = "01234 567890" } })
                                        @Html.ValidationMessageFor(model => model.Telephone, "", new { @class = "text-danger" })
                                    </div>
                                </div>
                                <div class="row">
                                    <div class="col-md-4 col-md-offset-1">
                                        @Html.LabelFor(model => model.Email, htmlAttributes: new { @class = "control-label" })
                                        @Html.EditorFor(model => model.Email, new { htmlAttributes = new { @class = "form-control", placeholder = "[email protected]" } })
                                        @Html.ValidationMessageFor(model => model.Email, "", new { @class = "text-danger" })
                                    </div>
                                    <div class="col-md-4 col-md-offset-1">
                                        @Html.LabelFor(model => model.ConfirmEmail, htmlAttributes: new { @class = "control-label" })
                                        @Html.EditorFor(model => model.ConfirmEmail, new { htmlAttributes = new { @class = "form-control", placeholder = "[email protected]" } })
                                        @Html.ValidationMessageFor(model => model.ConfirmEmail, "", new { @class = "text-danger" })
                                    </div>
                                </div>
                            </div>
                            <h3 class="text-success col-md-offset-1">Competition Licence</h3>
                            <div class="form-group">
                                <div class="row">
                                    <div class="col-md-4 col-md-offset-1">
                                        @Html.LabelFor(model => model.CompLicenceNo, htmlAttributes: new { @class = "control-label" })
                                        @Html.EditorFor(model => model.CompLicenceNo, new { htmlAttributes = new { @class = "form-control", placeholder = "123456" } })
                                        @Html.ValidationMessageFor(model => model.CompLicenceNo, "", new { @class = "text-danger" })
                                    </div>
                                    <div class="col-md-3 col-md-offset-1">
                                        @Html.LabelFor(model => model.SelectedLicenceTypeId, htmlAttributes: new { @class = "control-label" })
                                        @Html.EditorFor(model => model.SelectedLicenceTypeId, new { htmlAttributes = new { @class = "form-control" } })
                                        @Html.ValidationMessageFor(model => model.SelectedLicenceTypeId, "", new { @class = "text-danger" })
                                    </div>
                                </div>
                            </div>
                            <h3 class="text-success col-md-offset-1">Personal Details</h3>
                            <h4 class="text-success col-md-offset-1">Why do we need this information?</h4>
                            <p>To make it easier for you to enter events here on Grass Roots Clicks we gatther certain information that we can then populate into your entry. Why do we need a date of birth? Organisers gain great benefit form knowing what ages are taking part in their events. We dont share your date of birth, we use your current age to help the organisers and also tailor the entry form to you e.g. if your under 18 we'll ask you for parental permission for some events.</p>
                            <div class="form-group">
                                <div class="row">
                                    <div class="col-md-3 col-md-offset-1">
                                        @Html.LabelFor(model => model.DateOfBirth, htmlAttributes: new { @class = "control-label" })
                                        @Html.EditorFor(model => model.DateOfBirth, new { htmlAttributes = new { @class = "form-control", placeholder = "01/12/80" } })
                                        @Html.ValidationMessageFor(model => model.DateOfBirth, "", new { @class = "text-danger" })
                                    </div>
                                </div>
                                <div class="row">
                                    <div class="col-md-4 col-md-offset-1">
                                        @Html.LabelFor(model => model.NOKFirstName, htmlAttributes: new { @class = "control-label" })
                                        @Html.EditorFor(model => model.NOKFirstName, new { htmlAttributes = new { @class = "form-control", placeholder = "Jane" } })
                                        @Html.ValidationMessageFor(model => model.NOKFirstName, "", new { @class = "text-danger" })
                                    </div>
                                    <div class="col-md-4 col-md-offset-1">
                                        @Html.LabelFor(model => model.NOKLastName, htmlAttributes: new { @class = "control-label" })
                                        @Html.EditorFor(model => model.NOKLastName, new { htmlAttributes = new { @class = "form-control", placeholder = "Smith" } })
                                        @Html.ValidationMessageFor(model => model.NOKLastName, "", new { @class = "text-danger" })
                                    </div>
                                </div>
                                <div class="row">
                                    <div class="col-md-4 col-md-offset-1">
                                        @Html.LabelFor(model => model.NOKTelephone, htmlAttributes: new { @class = "control-label" })
                                        @Html.EditorFor(model => model.NOKTelephone, new { htmlAttributes = new { @class = "form-control", placeholder = "07234 567890" } })
                                        @Html.ValidationMessageFor(model => model.NOKTelephone, "", new { @class = "text-danger" })
                                    </div>
                                    <div class="col-md-4 col-md-offset-1">
                                        @Html.LabelFor(model => model.RelationshipTypeId, htmlAttributes: new { @class = "control-label" })
                                        @Html.EditorFor(model => model.RelationshipTypeId, new { htmlAttributes = new { @class = "form-control" } })
                                        @Html.ValidationMessageFor(model => model.RelationshipTypeId, "", new { @class = "text-danger" })
                                    </div>
                                </div>
                                <div class="row">
                                    <div class="col-md-7 col-md-offset-1">
                                        @Html.LabelFor(model => model.Dietary, htmlAttributes: new { @class = "control-label" })
                                        @Html.EditorFor(model => model.Dietary, new { htmlAttributes = new { @class = "form-control", placeholder = "Vegetarian" } })
                                        @Html.ValidationMessageFor(model => model.Dietary, "", new { @class = "text-danger" })
                                    </div>
                                </div>
                            </div>
                            <h3 class="text-success col-md-offset-1">Password</h3>
                            <div class="form-group">
                                <div class="row">
                                    <div class="col-md-4 col-md-offset-1">
                                        @Html.LabelFor(model => model.Password, htmlAttributes: new { @class = "control-label" })
                                        @Html.EditorFor(model => model.Password, new { htmlAttributes = new { @class = "form-control" } })
                                        @Html.ValidationMessageFor(model => model.Password, "", new { @class = "text-danger" })
                                    </div>
                                    <div class="col-md-4 col-md-offset-1">
                                        @Html.LabelFor(model => model.ConfirmPassword, htmlAttributes: new { @class = "control-label" })
                                        @Html.EditorFor(model => model.ConfirmPassword, new { htmlAttributes = new { @class = "form-control" } })
                                        @Html.ValidationMessageFor(model => model.ConfirmPassword, "", new { @class = "text-danger" })
                                    </div>
                                </div>
                            </div>
                            <h3 class="text-success col-md-offset-1">Contact</h3>
                            <div class="form-group">
                                <div class="row">
                                    <div class="col-md-9 col-md-offset-1">
                                        @Html.LabelFor(model => model.OtherOrgsGRC, htmlAttributes: new { @class = "control-label" })
                                    </div>
                                    <div class="col-md-1">
                                        @Html.CheckBoxFor(model => model.OtherOrgsGRC, new { @checked = "checked" })
                                        @Html.ValidationMessageFor(model => model.OtherOrgsGRC, "", new { @class = "text-danger" })
                                    </div>
                                </div>
                                <div class="row">
                                    <div class="col-md-9 col-md-offset-1">
                                        @Html.LabelFor(model => model.OtherClubEvents, htmlAttributes: new { @class = "control-label" })
                                    </div>
                                    <div class="col-md-1">
                                        @Html.CheckBoxFor(model => model.OtherClubEvents, new { @checked = "checked" })
                                        @Html.ValidationMessageFor(model => model.OtherClubEvents, "", new { @class = "text-danger" })
                                    </div>
                                </div>
                                <div class="row">
                                    <div class="col-md-9 col-md-offset-1">
                                        @Html.LabelFor(model => model.OtherOrgsOutside, htmlAttributes: new { @class = "control-label" })
                                    </div>
                                    <div class="col-md-1">
                                        @Html.CheckBoxFor(model => model.OtherOrgsOutside, new { @checked = "checked" })
                                        @Html.ValidationMessageFor(model => model.OtherOrgsOutside, "", new { @class = "text-danger" })
                                    </div>
                                </div>
                            </div>
                            <div class="form-group">
                                <div class="col-md-10 col-md-offset-1">
                                    <input type="submit" value="Register" class="btn btn-success btn-lg" />
                                </div>
                            </div>
                        }
                    </section>
                </fieldset>
            </form>
        </div>
    </div>


    <div class="col-md-4 panel panel-success">
        <div class="panel-heading">
            <h3 class="panel-title " align="center">Use another service to register</h3>
        </div>

        @Html.Partial("_ExternalLoginsListPartial", new GRCWebApp.Models.ExternalLoginListViewModel { ReturnUrl = ViewBag.ReturnUrl })

    </div>
</div>


@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
    @Scripts.Render("~/bundles/bootstrap")
<script type="text/javascript">
    $("#DateOfBirth").datepicker({
        format: "dd/mm/yyyy",
        startDate: "-120y",
        endDate: "-10y",
        startView: 2,
        calendarWeeks: true,
        defaultViewDate: { year: 1975, month: 01, day: 01 }
    });
    </script>
    }

Answer:

I fixed the problem by removing the form, fieldset and section tags at the beginning of the view.

Thanks to ekad for helping debug the problem


Related:


System.net.http.formatting causing issues with Newtonsoft.json


c#,asp.net,asp.net-mvc,json.net
My Windows service is in the same solution as a MVC project. The MVC project uses a reference to SignalR Client which requires Newtonsoft.Json v6 + the Windows service uses System.Net.Http.Formatting, which requires Newtonsoft.Json version 4.5.0.0. I assumed this would not be a problem, as I could just use a...

File IO Close() method error in ASP.NET MVC 6


asp.net-mvc,asp.net-mvc-6
I am doing a simple file IO in MVC6. I have added System.IO NuGet package. However, it gives me compile time error. VS IDE doesn't show any red mark when I type the code. The Close() method also appears in intellisense. Please help! My Code StreamWriter writer = System.IO.File.CreateText("some_valid_path"); writer.WriteLine("test");...

Export data from table in Pervasive


c#,pervasive
I want to export data from table programatically. And i wonder if it's even possible? The picture is from Pervasive, that the db-server I'm using. Please assist! :) ...

C# MySQL Parameters.AddWithValue


c#,mysql
Hello I found this code snippet for Adding Values to MySQL Commands in C# MySqlCommand command = connection.CreateCommand(); command.CommandText = "INSERT INTO tb_mitarbeiter (Vorname) VALUES (?name)"; command.Parameters.AddWithValue("?name", mitarbeiter); connection.Open(); command.ExecuteNonQuery(); Now I want to add data to more than one coloumn, but if i try it like this: command.Parameters.AddWithValue("?id", Projektid,...

Convert contents of an XmlNodeList to a new XmlDocument without looping


c#,xml,xpath,xmldocument,xmlnodelist
I have Xml that I filter using XPath (a query similar to this): XmlNodeList allItems = xDoc.SelectNodes("//Person[not(PersonID = following::Person/PersonID)]"); This filters all duplicates from my original Persons Xml. I want to create a new XmlDocument instance from the XmlNodeList generated above. At the minute, the only way I can see...

SettingsProvider class - should it be in DAL or BLL project?


c#,data-access-layer,bll
I have in my application layers: Web, DAL and BLL. Where should I place SettingsProvider class (to get values from web.config)? I think it should be inside DAL project. Am I right? public class SettingsProvider : ISettingsProvider { public string UploadImagesPath { get { return ConfigurationManager.AppSettings["UploadImagesPath"]; } } .............. }...

Access manager information from Active Directory


c#,asp.net,active-directory
Attach is the picture of active directory, which i got from my IT department. Now i want to get the manager information in C#. NOTE: I am able to get all information of user but there isn't any key of manager, but IT department just gave me above attached...

SQL Server / C# : Filter for System.Date - results only entries at 00:00:00


c#,asp.net,sql-server,date,gridview-sorting
I have a connected SQL Server database in Visual Studio and am displaying its content in a grid. I created a dropdown menu with the column names as selectable options and a text field to filter for specific content, e.g., DropDown = "Start" - Textfield = 14.03.2015 = Filter Column...

Collect strings after a foreach loop


c#,xml,foreach
Is it possible to collect the strings after a foreach loop? For example: StringCollection col = new StringCollection(); XmlNodeList skillNameNodeList=SkillXML.GetElementsByTagName("name"); foreach (XmlNode skillNameNode in skillNameNodeList) { skillsName=skillNameNode.Attributes["value"].Value; } col.Add(skillsName); //Return System.Collections.Specialized.StringCollection I want to collect each skillsName and put them in a collection or a list so that I can...

Convert Date Time to IST


c#
I want to convert the date time to "Indian Standard Time", so i used the following code :- public static TimeZoneInfo INDIAN_ZONE = TimeZoneInfo.FindSystemTimeZoneById("Indian Standard Time"); writer.WriteLine("{0} {1}", indianTime.ToLongTimeString(), indianTime.ToLongDateString()); The above code gives me error :- System.TimeZoneNotFoundException: The time zone ID 'Indian Standard Time' was not found on the...

How to send Ctrl+S through SendKeys.Send() method to save a file(save as dialog)


c#,.net,windows,sendkeys
I need to save a file which is in an External application using SendKeys.Send() method. The keys needed to be sent are Ctrl+S. I wrote the below code, but its not working: SendKeys.SendWait("^%s?"); // to get the Save As dialog Thread.Sleep(5000); SetForegroundWindow(FindWindow(null, "Save As")); Thread.Sleep(5000); SendKeys.SendWait("xyz"); // Sending FileName ...

Regex to remove `.` from a sub-string enclosed in square brackets


c#,.net,regex,string,replace
I have this regex in C#: \[.+?\] This regex extracts the sub-strings enclosed between square brackets. But before doing that I want to remove . inside these sub-strings. For example, the string hello,[how are yo.u?]There are [300.2] billion stars in [Milkyw.?ay]. should become hello,[how are you?]There are [3002] billion stars...

How do I provide a collection of elements to a custom attached property?


c#,wpf,binding
I found a few examples online, and a few questions and answers here, but I just can't get it to work. I need a custom attached property that can take one or more target elements. For example... <ListView> <dd:MyDragDrop.DropBorders> <Binding ElementName="brdOne"/> <Binding ElementName="brdTwo"/> <Binding ElementName="brdThree"/> </dd:MyDragDrop.DropBorders> </ListView> I've also had...

Marshal struct in struct from c# to c++


c#,c++,marshalling
I have the following structures in C# and C++. C++: struct TestA { char* iu; }; struct TestB { int cycle1; int cycle2; }; struct MainStruct { TestA test; TestB test2; }; C#: [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Ansi, Pack = 1)] internal struct TestA { [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 36)] private string iu; public...

Aligning StackPanel to top-center in Canvas


c#,wpf,xaml,canvas
I'm trying to create an application which is supposed to measure quick reaction performance of it's user. The application starts up in full-screen mode and resizes it's elements accordingly to the screen resolution. The project was strongly inspired by training_aim_csgo2 map. It's mostly done, but here is the problem: I...

C# - Can't connect to remote MySQL server


c#,mysql
My problem is that I can't connect to my website remote MySQL server. I have read all answers in stackoverflow.com, but I can't find right answer. Here's my C# code: using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; namespace ConsoleApplication3 { class Program { static void Main(string[] args) { SqlConnection...

how can I add a column to IQueryable object and modify its values


c#,.net,linq,grid,devexpress
var packs = from r in new XPQuery<Roll>(session) select new { Number = r.number Selection = new bool() }; gcPack.DataSource = packs; I want to add another column to my grid control with: Selection = new bool(). It will be added to the grid but I can't change its...

MvcSiteMapProvider - Enhanced bootstrap dropdown menu


c#,twitter-bootstrap,asp.net-mvc-5,mvcsitemapprovider,mvcsitemap
I'm trying to build a menu like this: For reference I'm using this library https://github.com/behigh/bootstrap_dropdowns_enhancement @Html.MvcSiteMap().Menu("BootstrapMenuHelperModel") @model MenuHelperModel <nav class="navbar" role="navigation"> <div class="container-fluid menu-container"> <div class="collapse navbar-collapse"> <div class="navbar-header"> <span class="navbar-brand">FAR BACKOFFICE</span> </div> <ul class="nav nav-pills"> @foreach (var node in Model.Nodes) { if...

Is it possible to concactenate a DataBound value with a constant string in XAML DataBinding?


c#,xaml,windows-phone
To bind a value to a TextBlock we use the following syntax to display an <ItemName> property of a bounded object. <TextBlock Text="{Binding Path=ItemName}" /> But is there a syntax to use the above tag to concatenate the constant string 'Item' with the databounded property, in order display something like:...

Memory consumption when chaining string methods


c#,string,immutability,method-chaining
I know that string in C# is an immutable type. Is it true that when you chain string functions, every function instantiates a new string? If it is true, what is the best practice to do too many manipulations on a string using chaining methods?...

check if file is image


c#,asp.net,asp.net-mvc
I want to check if file is image. and then you will see a link where you can see the image. But the link only has to appear if file is link. I try it like this: if (!String.IsNullOrEmpty(item.FileName)) { var file = item.FileName; string[] formats = new string[] {...

C# Code design / Seperate classes for each TabControl


c#,oop,architecture,software-design,code-design
My main problem is that my tool grows and grows and I start loosing the focus on the different parts of my code. The main-Form got a docked tabControl at fullsize. I got 5 different tabs with for really different functions. So I can say my tool is splitted into...

How to declare var datatype in public scope in c#?


c#,linq
I write simple query with linq to sql : var query = (from p in behzad.GAPERTitles select new { p.id, p.gaptitle }).ToArray(); up code into the c# windows application ,windows form load event,and i want use up result into the button click event in this scope: private void button1_Click(object sender,...

MVC 5 OWIN login with claims and AntiforgeryToken. Do I miss a ClaimsIdentity provider?


asp.net-mvc,asp.net-mvc-4,razor,asp.net-mvc-5,claims-based-identity
I'm trying to learn Claims for MVC 5 OWIN login. I try'ed to keep it as simple as possible. I started with the MVC template and inserted my claims code (see below). I get an error when I use the @Html.AntiForgeryToken() helper in the View. Error: A claim of type...

Difference between application and module pipelines in Nancy?


c#,asp.net,nancy
I have seen in the documentation of Nancy, sometimes these two are referred distinctively. And also is there a difference in the Before/After hooks of these two pipelines?...

DialogBox with value verifications


c#,.net,winforms
For my application which deals with graphics, I've made a little DialogBox to set: Max; Min; Major Step (of the scale); Minor Step. Here's a screen capture: I want to validate a few things before allowing the user to click Ok: Max >= Min MaxScale >= MinScale. But it's not...

Multiple Threads searching on same folder at same time


c#,multithreading,file-search
Currently I have a .txt file of about 170,000 jpg file names and I read them all into a List (fileNames). I want to search ONE folder (this folder has sub-folders) to check if each file in fileNames exists in this folder and if it does, copy it to a...

C# PCL HMACSHAX with BouncyCastle-PCL


c#,bouncycastle,portable-class-library
I want to implement this logic in portable C# class: static JsonWebToken() { HashAlgorithms = new Dictionary<JwtHashAlgorithm, Func<byte[], byte[], byte[]>> { { JwtHashAlgorithm.HS256, (key, value) => { using (var sha = new HMACSHA256(key)) { return sha.ComputeHash(value); } } }, { JwtHashAlgorithm.HS384, (key, value) => { using (var sha = new...

How to Customize Visual Studio Setup


c#,visual-studio,setup-project
I have created a video chat application in c#. Now I wan to make a setup of it. I have created a setup using Visual studio's setup project but my client told me to customize the setup progress bar styles and other properties. i dont know how to do it....

How can I determine if an object of anonymous type is empty?


c#,.net
I am sure the answer to this is quite simple but I am trying to write an if statement (C# 5.0) to determine whether or not an anonymous type is empty or not. Here is a simplified version of my code: public void DoSomething(object attributes) { // This is the...

Why is the task is not cancelled when I call CancellationTokenSource's Cancel method in async method?


c#,asynchronous,task,cancellationtokensource,cancellation-token
I created a small wrapper around CancellationToken and CancellationTokenSource. The problem I have is that the CancelAsync method of CancellationHelper doesn't work as expected. I'm experiencing the problem with the ItShouldThrowAExceptionButStallsInstead method. To cancel the running task, it calls await coordinator.CancelAsync();, but the task is not cancelled actually and doesn't...

Unconstrained type parameters casting


c#,.net,types,casting
My situation: interface ISomeInterface { void DoSmth<T>(T other); } class Base : ISomeInterface { public virtual void DoSmth<T>(T other){ // for example do nothing } } class Derived<T2> : Base { Action<T2> MyAction {get;set;} public override void DoSmth<T>(T other){ if(typeof(T2).IsAssignableFrom(typeof(T))) MyAction((T2) other); } } This gives me an error: Cannot...

Regex that allow void fractional part of number


c#,regex
@"[+-]?\d+(\.\d+)?" -this is a regex I have wrote for numbers it allows [+-] minus before the number digits before and digits after the point the question is how to change this to allow "not finished" values so that input of "5." - is fine too ?...

Error when building an XDocument


c#,xml,linq,xpath,linq-to-xml
Using the following example xml containing one duplicate: <Persons> <Person> <PersonID>7506</PersonID> <Forename>K</Forename> <Surname>Seddon</Surname> <ChosenName /> <MiddleName /> <LegalSurname /> <Gender>Male</Gender> </Person> <Person> <PersonID>6914</PersonID> <Forename>Clark</Forename> <Surname>Kent</Surname> <ChosenName>Clark</ChosenName> <MiddleName />...

Catch concurrency exception in EF6 to change message to be more user friendly


c#,asp.net,.net,entity-framework,entity-framework-6
I am using EF6.1 and i would like to change the message to a more system specific message when the below exception is thrown. Store update, insert, or delete statement affected an unexpected number of rows (0) Now, my problem is i cannot seem to catch the exception? I have...

Validate a field only if it is populated


c#,wpf,idataerrorinfo
I am having a problem with validating phone numbers. In our system we have two phone numbers which you can store. The problem I am having is that these are optional fields. So I want it to validate the phone number IF and only IF the user has tried to...

C# XML: System.InvalidOperationException


c#,xml
I have been learning C#'s XML with a project however I keep getting the InvalidOperationException. I have put the code below XmlTextWriter writer = new XmlTextWriter(path, System.Text.Encoding.UTF8); writer.WriteStartDocument(true); writer.Formatting = Formatting.Indented; writer.Indentation = 4; writer.WriteStartElement("User Info"); writer.WriteStartElement("Name"); writer.WriteString(userName); writer.WriteEndElement(); writer.WriteStartElement("Tutor Name"); writer.WriteString(tutorName); writer.WriteEndElement();...

Foreign key in C#


c#,sql,sql-server,database
I have two tables, A and B, in a dataset in SQL Server; I have created a connection to the dataset in a c# project in visual studio. How can I create a foreign key ( A is the parent) between my two tables ? I want to create the...

Update list of items in c#


c#,linq,list,updates
I would like to know if you can suggest me an efficient way to update a list of items in c#. Here is a generic example: If CurrentList is [ {Id: 154, Name: "George", Salary: 10 000} {Id: 233, Name: "Alice", Salary: 10 000}] And NewList is [ {Id: 154,...

Load XML to list using LINQ [duplicate]


c#,xml,linq
This question already has an answer here: XDocument to List of object 1 answer I have following XML: <?xml version="1.0" encoding="utf-8"?> <start> <Current CurrentID="5"> <GeoLocations> <GeoLocation id="1" x="78492.61" y="-80973.03" z="-4403.297"/> <GeoLocation id="2" x="78323.57" y="-81994.98" z="-4385.707"/> <GeoLocation id="3" x="78250.57" y="-81994.98" z="-4385.707"/> </GeoLocations> <Vendors> <Vendor id = "1" x="123456" y="456789" z="0234324"/>...

Visual Studio Assembly force-installs Target Framework


c#,.net,visual-studio-2013,.net-framework-version
I have this Assembly targeted at .NET 3.5. The code will work on later versions as well, but I like this to work on Windows XP. I mean, .NET is backwards compatible, right? I can run apps for .NET 3.5 on Windows 8.1. However, when I run my own assembly,...

Get object by attribute value [duplicate]


c#,reflection,custom-attributes,spring.net
This question already has an answer here: How enumerate all classes with custom class attribute? 4 answers I have a set of classes which implement a common interface and are annotated with a business domain attribute. By design, each class is annotated with different parametrization [Foo(Bar=1)] public class EntityA...

Checkbox to be checked on having value Y


asp.net-mvc,knockout.js
I have a checkbox bound to a viewmodel's observable property, whose value will be Y or N. I want the the checkbox to be checked when the value is Y and unchecked when the value is N. How to achieve this? I am able to achieve it if the value...

How to return result while applying Command query separation (CQS)


c#,design-patterns,cqrs,command-query-separation
I am separating my query and command on service side like this: public class ProductCommandService{ void AddProduct(Product product); } public interface ProductQueryService{ Product GetProduct(Guid id); Product[] GetAllProducts(); } Command Query Separation accepts that a method should change state or return a result. There is no problem. public class ProductController: ApiController{...

Index was out of range. Must be non-negative or less than size of collection [duplicate]


c#
This question already has an answer here: What is an “index out of range” exception, and how do I fix it? [duplicate] 1 answer Trying to run a delete application in C#. If there is more than 10 files in a directory, delete the oldest file, and iterate again....

deployment of a site asp.net and iis


c#,asp.net,iis
I know this is for some of you a stupid question but for me is a real problem. I have never deployed a site before What i have done so far: 1) publish the site from visual studio to a folder. 2) added to iis for testing everything works great...

while Inherit style in WPF it affect parent style


c#,xaml,styles,wpf-controls
In WPF i have a style for the control like below, <Style TargetType="local:CustomControl"> <Setter Property="Background" Value="Transparent" /> <Setter Property="BorderBrush" Value="Gray" /> <Setter Property="BorderThickness" Value="0,0,0,1" /> <Setter Property="Padding" Value="3,0,3,0" /> <Setter Property="IsTabStop" Value="False" /> <Setter Property="VerticalContentAlignment" Value="Center" /> </Style> Now i need to override customcontrol border for some other place like...