enter image description hereits just a sample i want to store my all text field also clicked one radio button value also be stored.give some sql table structure

Example enter image description here

I want to convert this code into simple input type text or want to use class inside @htmltexboxenter image description here

Like min and max length or jquery validation not want to use required

Here is my function to try and request USPS api. This is the link on how to get the api (https://www.usps.com/business/web-tools-apis/general-api-developer-guide.pdf). Trying to use Test2 from the document above to validate my address. I am not asking for a solution, I just need guidance on what steps to take next.

(Btw each create is roughly the same)

public static string GetAddress(string address2, string city, string state, string zip, string url, string id)
{
    string api = "AddressValidateRequest";

    string urlOpen = url + api + "&XML=<AddressValidateRequest USERID=\"" + id + "\"><Address ID =\"1\">";
    string urlClose = "</Address></AddressValidateRequest>";

    string xml = CreateAddress1XML(address2) + CreateAddress2XML(address2) + CreateCityXML(city) + CreateStateXML(state) + CreateZip5XML(zip) + CreateZip4XML(zip);

    string requestUrl = urlOpen + xml + urlClose;

    XmlDocument doc = new XmlDocument();

    doc.Load(requestUrl);

    XmlNodeList addresslist = doc.GetElementsByTagName("Address2");

    return addresslist[0].InnerText;
}
public static string CreateAddress1XML(string address)
{

    XmlDocument doc = new XmlDocument();
    XmlElement address1 = doc.CreateElement("Address1");
    address1.InnerText = address;

    doc.AppendChild(address1);

    return doc.OuterXml;
}

Someone posted the same question here and I followed every step and yet it still doesn't work. I made many working projects before with the same feature.

So when a user registers for a new account, he fills out a form and Selects from 2 dropdownlists UserType and Region.

everything else works fine and when the form is posted. a new record of Region and UserType is created in the DB and linked with new IDs.

here is my IdentityModel:

 public class ApplicationUser : IdentityUser
{
    [Required]
    public string Name { get; set; }

    public UserType UserType { get; set; }
    public int UserTypeId { get; set; }

    public Region Region { get; set; }
    public int RegionId { get; set; }

    [Display(Name ="Summoner Name")]
    public string SummonerName { get; set; }

    public int AccountId { get; set; }

    public async Task<ClaimsIdentity> 
    GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
    // etc.....

here is my Register Action in AccountController

public async Task<ActionResult> Register(RegisterViewModel model)
    {
        if (ModelState.IsValid)
        {
            var UserTypeInDb = _context.UserTypes.Single(u => u.Id == model.UserTypeId);
            var RegionInDb = _context.Regions.Single(u => u.Id == model.RegionId);


            var user = new ApplicationUser {
                UserName = model.Email,
                Email = model.Email,
                Name = model.Name,
                Region = RegionInDb,
                UserType = UserTypeInDb
            };
            var result = await UserManager.CreateAsync(user, model.Password);
            if (result.Succeeded)
            {
                await SignInManager.SignInAsync(user, isPersistent:false, rememberBrowser:false);

                // For more information on how to enable account confirmation and password reset please visit https://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
        var viewModel = new RegisterViewModel()
        {
            Regions = _context.Regions.ToList(),
            UserTypes = _context.UserTypes.ToList()
        };
        return View(viewModel);
    }

the 2 variables UserTypeInDb and RegionInDb contain the right records with the correct IDs.

so what is wrong exactly? and thanks

trying to get number of selected options in a hidden multiselect list, when running the JavaScript in Chrome, Opera and Firefox it is returning the number of selected values.

When running the same JavaScript in IE 11 the length is returned as 0.

In the cshtml the dropdownlists are defined as such:

    <div id="fullKeyIndicators" class="hidden">
       <input id="all_indicators" class="select_all" type="button" title="Select All" value="Select All" onclick="selectAll('fullList', 'all_indicators')"/>
       @Html.DropDownList("DownloadKeyIndicatorId", Model.DownloadKeyIndicatorList, new {id = "fullList", name = "DownloadKeyIndicatorId", @class = "multi-select-download", multiple = "multiple"})
    </div>
    <div id="keyIndicatorsOnlyAllInTx" class="hidden">
       <input id="all_indicators_allintx" class="select_all" type="button" title="Select All" value="Select All" onclick="selectAll('allInTxOnly', 'all_indicators_allintx')"/>
       @Html.DropDownList("DownloadKeyIndicatorId", Model.DownloadKeyIndicatorAllInTxList, new {id = "allInTxOnly", name = "DownloadKeyIndicatorId", @class = "multi-select-download", multiple = "multiple"})
    </div>
    <div id="keyIndicatorsOnlyNewTx" class="hidden">
       <input id="all_indicators_newtx" class="select_all" type="button" title="Select All" value="Select All" onclick="selectAll('newTxOnly', 'all_indicators_newtx')"/>
       @Html.DropDownList("DownloadKeyIndicatorId", Model.DownloadKeyIndicatorNewTxList, new {id = "newTxOnly", name = "DownloadKeyIndicatorId", @class = "multi-select-download", multiple = "multiple"})
    </div>    

the JavaScript I am using is provided below:

<script type="text/javascript">
    $('#export').click(function(e) {
        var inTreatmentCohortTotal = $('input[name="DownloadInTreatmentCohortId"]:checked').length;
        var keyIndicatorTotal = 0;
        var cohortArray = [];

        $('input[name="DownloadInTreatmentCohortId"]:checked').each(function() {
            cohortArray.push($(this).val());
        });

        if (inTreatmentCohortTotal === 0) {
            keyIndicatorTotal = 0;
        } else if ($.inArray("AllInTx", cohortArray) > -1 && ($.inArray("NewTx", cohortArray) === -1)) {
            var keyIndicatorTotal = $('#allInTxOnly option:selected').length;
        } else if ($.inArray("NewTx", cohortArray) > -1 && ($.inArray("AllInTx", cohortArray) === -1)) {
            var keyIndicatorTotal = $('#newTxOnly option:selected').length;
        } else if ($.inArray("NewTx", cohortArray) > -1 && ($.inArray("AllInTx", cohortArray) > -1)) {
            var keyIndicatorTotal = $('#fullList option:selected').length;
        }

        var reportingPeriodTotal = $('#DownloadPeriodEndDate option:selected').length;
        var substanceCategoryTotal = $('#DownloadSubstanceCategoryId option:selected').length;
        var genderTotal = $('#DownloadGenderId option:selected').length;

        if (inTreatmentCohortTotal >= 1 &&
            keyIndicatorTotal >= 1 &&
            reportingPeriodTotal >= 1 &&
            substanceCategoryTotal >= 1 &&
            genderTotal >= 1) {

            localStorage.removeItem('ValidationMessage');
            $('#exportValidation').addClass('hidden');

            $('#csvExportForm').submit();
            setTimeout(function () {
                    window.location.reload(1);
                },
                5000);
        }
        else {

            localStorage.setItem("ValidationMessage", true);

            $("#csvExportForm").submit(function(e) {
                e.preventDefault();
            });

            window.location.href = window.location.href;
        }
    });

    $(document).ready(function() {
        if (localStorage.getItem("ValidationMessage") !== null) {
            $('#exportValidation').removeClass('hidden');
        }
    });

    $('.touchMultiSelect').on('click', function (e) {
        if (e.hasOwnProperty('originalEvent')) {
            $('.touchMultiSelect').addClass('opened');
        }
    });
</script>

The section that is causing the issue is:

if (inTreatmentCohortTotal === 0) {
            keyIndicatorTotal = 0;
        } else if ($.inArray("AllInTx", cohortArray) > -1 && ($.inArray("NewTx", cohortArray) === -1)) {
            var keyIndicatorTotal = $('#allInTxOnly option:selected').length;
        } else if ($.inArray("NewTx", cohortArray) > -1 && ($.inArray("AllInTx", cohortArray) === -1)) {
            var keyIndicatorTotal = $('#newTxOnly option:selected').length;
        } else if ($.inArray("NewTx", cohortArray) > -1 && ($.inArray("AllInTx", cohortArray) > -1)) {
            var keyIndicatorTotal = $('#fullList option:selected').length;
        }

The variables reportingPeriodTotal, substanceCategoryTotal and genderTotal all work as expected in IE 11, I have provided the cshtml for one these multiselects as well:

@Html.DropDownList("DownloadSubstanceCategoryId", Model.DownloadSubstanceCategoryList, new {@class = "multi-select-download", multiple = "multiple"})

Does any one have any ideas why this happening and could a solution that works for all browser?

i need another dropdown but with the value selected into this dropdown:

@Html.dropdownlist("SearchString", new SelectList(ViewBag.Dat, ViewBag.searchstring), string.Empty, new {@class="chzn-select"})

It is possible create dropdown with the query and where condition with Razor?

Thank you for your help

I need to create Word (or Excel) reports in Razor Pages. What would 3rd party software you recommend?I need robust functionality but restricted with $. For now, it is 1 website.Thanks!

I have the following code in a Razor view:

<abbr title='@Localizer["AnswerTip"]'>
    <label asp-for="MyModelField" class="control-label"></label>
</abbr>

The translation works fine, except that the localized value in French has a single quote in it. Because of this, the html 'title' attribute value in French is truncated after the single quote.

Does anyone have a solution for this?

Here is an example of what it does:

  • Value in English = Can you help?
  • Translated value in French = Pouvez-vous m'aider?
  • Value that displays in French (truncated) = Pouver-vous m

Im migrating an application so this code was already working.

I have one angular function to create random avl input to test my api.

$scope.createAvl = function () {
    console.log($scope.avl); // for debug
    $scope.avl.push({
        'tracker_avl_id': getRandomArbitrary(0, 1000000, 1),
        'car_id': getRandomArbitrary(0, 10000, 1),
        'x_lat': getRandomArbitrary(-69, -66, 0),
        'y_long': getRandomArbitrary(8, 10, 0),
        'azimuth': getRandomArbitrary(0, 359, 1),
        'event_time': getRandomDate()
    });
};

As you can see the data is created and show properly on the page

enter image description here

Then the Save Avl function to send the data

$scope.saveAvl = function () {
    var data = $.param({
        avl_list: $scope.avl
    });

    var config = {
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8;'
        }
    };        

    $http.post('/Avl_Api/traffic_tracker_avl/putTrafficAvl', data, config)
    .success(function (data, status, headers, config) {            
        console.log('Sucess.....');           
    })
    .error(function (data, status, header, config) {
        $scope.ResponseDetails = "Data: " + data +
            "<hr />status: " + status +
            "<hr />headers: " + header +
            "<hr />config: " + config;
    });
};

The problem is on my controller Im getting 0 for coordinates x, y for all elements on avl_list all other fields are ok.

public partial class traffic_tracker_avl
{
    public int avl_id { get; set; }
    public long tracker_avl_id { get; set; }
    public long car_id { get; set; }
    public decimal x_lat { get; set; }
    public decimal y_long { get; set; }
    public int azimuth { get; set; }
    public System.DateTime event_time { get; set; }
    public Nullable<System.DateTime> created_at { get; set; }
}

[HttpPost]
public JsonResult putTrafficAvl(List<traffic_tracker_avl> avl_list)
{
    avl_list.ForEach(n => db.traffic_tracker_avl.Add(n));
    db.SaveChanges();
}

Im guessing have something to do with the decimal field? But is weird get 0 instead of truncate to integer. I double check and the data and the model field name are the same.

When I use

CustomUserDetails customUser = (CustomUserDetails) 
SecurityContextHolder.getContext().getAuthentication().getPrincipal();

It works but

@AuthenticationPrincipal(CustomUserDetails customUserDetails) returns null object

why? How can I solve this problem?


CustomUserDetails

public class CustomUserDetails extends User implements UserDetails,Serializable {

user is my data table object

...
....

public CustomUserDetails(final User user) {
    super(user);
}

@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
    return getRoles().stream().map(role -> new SimpleGrantedAuthority("ROLE_" + role.getRole())).collect(Collectors.toList());
}

....

CustomUserDetailsService

@Service
public class CustomUserDetailsService implements UserDetailsService{

@Autowired
private UserService userService;

@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
    Optional<User> user = userService.getByEmail(username);
    if(user == null) {
        return null;
    }

    user.orElseThrow(() -> new UsernameNotFoundException("Username not found"));

    CustomUserDetails userDetails = user.map(CustomUserDetails::new).get();

    return userDetails;
}

WebSecurityConfig

@Configuration
@EnableWebSecurity
public class WebSecurityConfig{
... 
..
.

@Configuration
    public static class HomeLoginConfig extends WebSecurityConfigurerAdapter{       

        @Autowired
        UserService userService;

        @Autowired
        private CustomUserDetailsService customUserDetailsService;


        @Override
        protected void configure(AuthenticationManagerBuilder auth) throws Exception {
            auth.userDetailsService(customUserDetailsService).passwordEncoder(bCryptPasswordEncoder());

...
..
..

Page Controller

@RequestMapping(value = {"/","/index","/home"})
public ModelAndView indexPage(@AuthenticationPrincipal CustomUserDetails userDetails) {
    ModelAndView mv = new ModelAndView("page");
    CustomUserDetails customUser = (CustomUserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    System.out.println("user detail @AuthenticationPrincipal "+userDetails.getFirstName());
    System.out.println("user detail getPrincipal" + customUser.getFirstName());

@AuthenticationPrincipal CustomUserDetails return null issue

but SecurityContextHolder.getContext().getAuthentication.getPrincipal return CustomUserDetails it is work fine

why @AuthenticationPrincipal didn't work?

I am currently developing an application that deals with displaying a scene for a fixed period of time before switching to a final scene with a button that takes you back to the main screen. However, I haven't been able to figure out how to do this. Below are my controller classes.

handleStart() is activated when a button is pushed and is what takes me to the scene I would only like to have displayed for a period of time.

package application.controller;

import java.io.IOException;
import javafx.event.ActionEvent;
import javafx.fxml.FXMLLoader;
import javafx.scene.Node;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;

public class MainController {
    public void handleHome(ActionEvent e) throws IOException {
        changeScene(e, "/Start.fxml");
    }

    public void handleStart(ActionEvent e) throws IOException {
        changeScene(e, "/Workout.fxml");
    }

    public void changeScene(ActionEvent e, String path) throws IOException {
        Parent parent = FXMLLoader.load(getClass().getResource(path));
        Scene scene = new Scene(parent);
        scene.getStylesheets().add("/application/app.css");
        Stage window = (Stage)((Node)e.getSource()).getScene().getWindow();
        window.setScene(scene);
        window.show();
    }
}

This is where I am stuck. In my method startCountDown() I am running a timer that is decrementing countDown every second. However, when the countDown reaches 0 the scene never changes. How should I approach this problem differently to complete this task?

package application.controller;

import java.io.IOException;
import java.net.URL;
import java.util.ResourceBundle;
import java.util.Timer;
import java.util.TimerTask;
import javafx.application.Platform;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.stage.Stage;

public class WorkoutController implements Initializable {

    Timer timer = new Timer();
    int countDown = 30;

    @FXML Label secondsLabel;

    public void initialize(URL arg0, ResourceBundle arg1) {
        startCountDown();
    }

    public void startCountDown() {
        timer.schedule(new TimerTask() {
        @Override
            public void run() {
            Platform.runLater(new Runnable() {
               public void run() {
                   countDown--;

                    if (countDown == 0)
                        try {
                            changeScene("/Completed.fxml");
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        timer.cancel();
              }
            });
        }
        }, 1000, 1000); //Every 1 second
    }

    public void changeScene(String path) throws IOException {
        Parent parent = FXMLLoader.load(getClass().getResource(path));
        Scene scene = new Scene(parent);
        scene.getStylesheets().add("/application/app.css");
        Stage window = (Stage)secondsLabel.getScene().getWindow();
        window.setScene(scene);
        window.show();
    }
}

I think I'm going crazy perhaps. I've got a controller (TrainingOfficer) which has some methods, but in particular it has Index():

[HttpGet]
public ActionResult Index()
{  
//does stuff, returns a view
}

I then wanted to link to that controller/action, so I wrote out:

<a class="nav-link" asp-area="" asp-controller="TrainingOfficer" asp-action="Index">Training</a>

But unfortunately razor drops the "Index" method and simply returns (not there is no /Index):

<a class="nav-link" href="/TrainingOfficer">Training</a>

Which is all well and good, except that when I leave "/Index" off the url it now just prints "value" to the screen:

https://i.imgur.com/4m0OdSC.jpg

Continuing on with the weirdness:

  1. If I travel to TrainingOfficer/Index, it works fine and as expected.
  2. If I rename Index to IndexLOL, and put IndexLOL as the asp-action in the link, the href tag looks great and everything works.

Why is this having such a problem with a method named Index?

Even odder, I'm pretty sure this worked just fine with no changes for a month and then recently started showing this behavior. I upgraded my .Net Core nuget package so perhaps that's the culprit.

I think I'm going crazy perhaps. I've got a controller (TrainingOfficer) which has some methods, but in particular it has Index():

[HttpGet]
public ActionResult Index()
{  
//does stuff, returns a view
}

I then wanted to link to that controller/action, so I wrote out:

<a class="nav-link" asp-area="" asp-controller="TrainingOfficer" asp-action="Index">Training</a>

But unfortunately razor drops the "Index" method and simply returns (not there is no /Index):

<a class="nav-link" href="/TrainingOfficer">Training</a>

Which is all well and good, except that when I leave "/Index" off the url it now just prints "value" to the screen:

https://i.imgur.com/4m0OdSC.jpg

Continuing on with the weirdness:

  1. If I travel to TrainingOfficer/Index, it works fine and as expected.
  2. If I rename Index to IndexLOL, and put IndexLOL as the asp-action in the link, the href tag looks great and everything works.

Why is this having such a problem with a method named Index?

Even odder, I'm pretty sure this worked just fine with no changes for a month and then recently started showing this behavior. I upgraded my .Net Core nuget package so perhaps that's the culprit.

I need your help with this one, I don't know if it is possible.

Imagine a RadioButtonList populated from a Database using a databind from vb codebehind looking like this;

[1]  - Apple      -    Fruit  
[2]  - Banana      -   Fruit  
[3]  - Beetroot    -   Vegetable 
[4]  - Orange      -   Fruit   
[5]  - Strawberry  -   Fruit  
[6]  - Carrot      -   Vegetable  
[7]  - Potato      -   Vegetable

Now I want to make it look like this;

- [Fruit]
     - Apple
     - Banana
     - Orange
     - Strawberry
- [Vegetable]
     - Beetroot
     - Carrot
     - Potato

I think I am able to group the radio button somehow or change the label. I also thought about using a tree node which I have not used before.

Is there a way to resize the GridView height everytime an item is added or deleted? Lets say I have an initial heigth and everytime I add an item I want to resize the gridview +20px or -20px if I delete an item. Or even better, maybe an autoresize is available?

I am a beginner to ASP and I have this code. It suppose to display the sum, product, and average of three numbers from an array in separate text boxes once the button"calculate" is pressed. However, whenever I put three values in text boxes and press calculate it just shows zeros!

protected void MathOps(object sender, EventArgs e)
{
    double[] arr = new double[3];

    double sum = 0;
    double product = 0;
    double average = 0;

    for (int i = 0; i < arr.Length; i++)
    {
        sum += arr[i];
        product *= arr[i];
        average = sum / arr.Length;

        TextBox6.Text = sum.ToString();
        TextBox7.Text = product.ToString();
        TextBox8.Text = average.ToString();
    }
}

This is a picture of the form for more clarification

After some lengthy experimentation, I discovered that having this line of code on the aspx side:

<EditItemTemplate>  
    <asp:DropDownList ID="ddl_Project_Owner" runat="server" Width="70px" 
         DataTextField="Project_Owner" DataValueField="Project_Owner" 
         SelectedValue='<%# Bind("Project_Owner") %>' >
    </asp:DropDownList>  
</EditItemTemplate>  

caused an index error, but removing the SelectedValue='<%# Bind("Project_Owner") %>' piece allowed the gridview to function properly. The only thing is, when the row goes into edit mode, the dropdown is not filled with the current value. It's blank. I'd like to fill it with the current value.

On the code-behind side, I use this code to fill the dropdown:

protected void DataGrid_ResourceAllocation_EditCommand(object sender, GridViewEditEventArgs e)
{
    DataGrid_ResourceAllocation.EditRowStyle.BackColor = System.Drawing.Color.LightYellow;
    DataGrid_ResourceAllocation.EditIndex = e.NewEditIndex;
    LoadResourceAllocationGrid();
    //DataGrid_ResourceAllocation.DataBind();


    SqlConnection conn = GetConnection();
    int RAC = DataGrid_ResourceAllocation.Rows.Count;

    GridViewRow row = DataGrid_ResourceAllocation.Rows[e.NewEditIndex];

    //*********************************************************
    //******** Fill in all your dropdown lists here ***********
    //*********************************************************

    DropDownList ddList = row.FindControl("ddl_Project_Owner") as DropDownList;
    string ddListVal = ddList.SelectedValue;

    //DropDownList ddList = (DropDownList)e.Row.FindControl("ddl_Project_Owner");
    if (ddList != null)
    {
        //bind dropdown-list
        string sqlStr = "Select distinct Project_Owner from tblProjectHealth order by Project_Owner";
        DataSet ds = new DataSet();

        conn.Open();
        SqlCommand cmd = new SqlCommand(sqlStr, conn);
        SqlDataAdapter ad = new SqlDataAdapter(cmd);
        ad.Fill(ds);

        ddList.DataSource = ds;
        ddList.DataTextField = "Project_Owner";
        ddList.DataValueField = "Project_Owner";
        ddList.DataBind();

        //DataRowView dr = e.Row.DataItem as DataRowView;
        //ddList.SelectedItem.Text = dr["category_name"].ToString();
        ddList.SelectedValue = ddListVal;
    }

}

I tried that "ddListVal" variable because I thought it might work, but it didn't, so you can ignore that.

Can anyone help me get my dropdown to populate with the current value that exists for that field in that record?

I have 30 textboxes available for user input and a Submit button that needs to insert only the textboxes with values. Currently, I have the empty text boxes receiving a "null" value, but this inserts the word "null" into the database instead of leaving it empty.

   protected void btnSubmit_Click(object sender, EventArgs e)
{

    String conString = @"Data Source=184.168.47.21;Initial Catalog=RecruitPursuit;Persist Security Info=True;User ID=RecruitPursuit;Password=Recruit20!8";
    SqlConnection con = new SqlConnection(conString);

    //create a command behavior object
    String cmdString = "INSERT INTO [Positions]( Sport_ID, Position)" +
    "VALUES (@Sport_ID, @Position1), (@Sport_ID, @Position2), (@Sport_ID, @Position3), (@Sport_ID, @Position4), (@Sport_ID, @Position5), (@Sport_ID, @Position6), (@Sport_ID, @Position7), (@Sport_ID, @Position8), (@Sport_ID, @Position9), (@Sport_ID, @Position10), (@Sport_ID, @Position11), (@Sport_ID, @Position12), (@Sport_ID, @Position13), (@Sport_ID, @Position14), (@Sport_ID, @Position15), (@Sport_ID, @Position16), (@Sport_ID, @Position17), (@Sport_ID, @Position18), (@Sport_ID, @Position19), (@Sport_ID, @Position20), (@Sport_ID, @Position21), (@Sport_ID, @Position22), (@Sport_ID, @Position23), (@Sport_ID, @Position24), (@Sport_ID, @Position25), (@Sport_ID, @Position26), (@Sport_ID, @Position27), (@Sport_ID, @Position28), (@Sport_ID, @Position29), (@Sport_ID, @Position30)";
    SqlCommand cmd = new SqlCommand(cmdString, con);

//This is only an example using 5 positions.

    SqlParameter param0 = new SqlParameter();
    param0.ParameterName = "@Sport_Id";
    param0.Value = Session["SportID"];
    cmd.Parameters.Add(param0);


    SqlParameter param1 = new SqlParameter();
    param1.ParameterName = "@Position1";
    param1.Value = TextBoxOpt1.Text;
    cmd.Parameters.Add(param1);


    SqlParameter param2 = new SqlParameter();
    param2.ParameterName = "@Position2";

    if (TextBoxOpt2.Text != String.Empty)
    {

        param2.Value = TextBoxOpt2.Text;

    }

    if (TextBoxOpt2.Text == String.Empty)
    {

        param2.Value = "null";

        //cmd.Parameters.AddWithValue("@Position2", param2==null ? (object)DBNull.Value : param2);
    }
    cmd.Parameters.Add(param2);


    SqlParameter param3 = new SqlParameter();
    param3.ParameterName = "@Position3";
    if (TextBoxOpt3.Text != String.Empty)
    {
        param3.Value = TextBoxOpt3.Text;
    }

    if (TextBoxOpt3.Text == String.Empty)
    {
        param3.Value = "null";
    }
     cmd.Parameters.Add(param3);

    SqlParameter param4 = new SqlParameter();
    param4.ParameterName = "@Position4";
    param4.Value = TextBoxOpt4.Text;

    if (TextBoxOpt4.Text != String.Empty)
    {
        param4.Value = TextBoxOpt4.Text;
    }
    if (TextBoxOpt4.Text == String.Empty)
    {
        param4.Value = "null";
    }
    cmd.Parameters.Add(param4);

    SqlParameter param5 = new SqlParameter();
    param5.ParameterName = "@Position5";
    param5.Value = TextBoxOpt5.Text;
    if (TextBoxOpt5.Text != String.Empty)
    {
        param5.Value = TextBoxOpt5.Text;
    }
    if (TextBoxOpt5.Text == String.Empty)
    {
        param5.Value = "null";
    }
    cmd.Parameters.Add(param5);

}

I just want to write a small asp.net e-commerce web application, can you please help out to me to find the source code for this application in c#?

Thank you!

I have a form in ASP.NET MVC5 that uses FormMethod.Post I have a Create button that submits the form, but how would I get it to work so that if you click Create then it disables the button. I have tried:

onclick="this.disabled = true"

But then the form is not submitted, hower when it is removed it allows you to add multiple records when clicking Create

This is my code for the form:

    @section scripts {
    @Scripts.Render("~/bundles/jqueryajaxval")
    @Scripts.Render("~/bundles/jqueryval")

    <script language="javascript" type="text/javascript">
        // cancel
        $(document).on("click",
            "#CancelForm",
            function(e) {
                var uri = '@Html.Raw(Url.Action("Index", "Membership"))';
                window.location = uri;
                e.preventDefault();
            });

        // submit
        $(document).on("click", "#submitMembership", function(e) {
                // Perform Ajax request to check if CAE/IPI Number is unique.
                var caeipinumber = $('#addMembershipCAEIPINumber').val();
                if (caeipinumber) {
                    $.ajax({
                        url: '@Url.Action("IsCAEIPINumberUnique", "Membership")',
                        data: ({ 'caeipinumber': caeipinumber, 'personaIdToIgnore': null }),
                        type: 'POST',
                        async: false,
                        cache: false,
                        success: function(result) {
                            if (result.toLowerCase() == "false") {
                                // Number is not unique and already exists, so display validation error to the user.
                                e.preventDefault();
                                $('#addMembershipForm').validate().showErrors({ 'CAEIPINumber': 'CAE / IPI Number already exists!' });
                                return false;
                            }
                            return true;
                        },
                        error: function(xhr, status, error) {
                        }
                    });
                }
            });
    </script>
}

@section additionalStyles {

}

@section modal {

}

<article class="row">
    <h1 class="pageTitle artistHeader fw200 mb20 mt10">@ViewBag.Title</h1>

    <div class="col-md-1"></div>
    <div id="createMembership" class="col-md-10 formContainer">
        <div class="panel">
            <div class="panel-heading">
                <span class="panel-title">
                    <i class="glyphicon glyphicon-pencil"></i>&nbsp;Details of New Membership
                </span>
            </div>

            @using (Html.BeginForm("AddMembership", "Membership", FormMethod.Post, new { id = "addMembershipForm", role = "form", @class = "theme-primary form-horizontal" }))
            {
                <fieldset>
                    <legend style="display: none">Add Membership Form</legend>
                    @Html.AntiForgeryToken()
                    @Html.ValidationSummary(true)
                    <div class="panel-body p25 fill bt0 pbn">
                        <div class="form-group">
                            @Html.LabelFor(x => x.MembershipName, new { @class = "control-label col-md-3" })
                            <div class="col-md-8">
                                @Html.TextBoxFor(x => x.MembershipName, new { id = "addMembershipName", @class = "form-control", placeholder = "Enter Membership Name..." })
                                @Html.ValidationMessageFor(x => x.MembershipName, string.Empty, new { @class = "text-danger" })
                            </div>
                        </div>
                        <div class="form-group">
                            @Html.LabelFor(x => x.CAEIPINumber, new { @class = "control-label col-md-3" })
                            <div class="col-md-8">
                                @Html.TextBoxFor(x => x.CAEIPINumber, new { id = "addMembershipCAEIPINumber", @class = "form-control", placeholder = "Enter CAE / IPI Number..." })
                                @Html.ValidationMessageFor(x => x.CAEIPINumber, string.Empty, new { @class = "text-danger" })
                            </div>
                        </div> 
                    </div>
                    <div class="panel-footer">
                        <div class="text-center">
                            <input type="button" class="btn btn-primary" id="CancelForm" value="Cancel" />
                            <input id="submitMembership" type="submit" class="btn btn-primary" value="Create" />
                        </div>
                    </div>
                </fieldset>
            }
        </div>
    </div>
    <div class="col-md-1"></div>
</article>

Starting April 19, 12:40pm, 3 of our webapps hosted by azure (asp.net 64bit 4.7) started throwing random error 400 and 500, going down for 5 minutes every once in a while.

This is happening in the East US, North Europe and Australia East centers.

Needless to say, the web app was not modified in the past month.

We are getting these errors even on simple resource files like JS and CSS.

For example: https://apps.kwizcom.com/Products/APLFE/Scripts/kwizcom.aplfe.controller.core.js?rev=1.1.0.9

Would log this error: HTTP Error 400.0 - Bad Request ASP.NET detected invalid characters in the URL.

Other requests (mostly to web REST api) will return: "The request could not be understood by the server due to malformed syntax."

Making the exact same request right after will return the content as expected.

And every now and then an error 500 will come up, usually bringing down the server for a short while.

Any clue why this could be happening? Feels like a new feature rolled out in Azure that causes this - anyone else experiencing the same issues?

Any insight or workaround will be greatly appreciated.