I'm trying to use a report viewer control, within a razor view, in the mvc 5 framework. But it don not know the correct way to do that can any one help me please

I have this controller which creates a List where T is a class model called GamingEvents.

    public async Task<IActionResult> Index(DateTime start, DateTime end)
        List<GamingEvents> gamingEventsListings = await sg.GenerateGameEventsSchedule();

        ViewData["RangeStart"] = start;
        ViewData["RangeEnd"] = end;

        return View(gamingEventsListings);

In my view I generate this table to display the data:

    @model List<GameManager.Models.GamingEvents>

    @foreach (var item in Model)
                @Html.DisplayFor(modelItem => item.GameId)
                @Html.DisplayFor(modelItem => item.GameName)
                @Html.DisplayFor(modelItem => item.DayNames)

Now, I want to send all this data to another controller. So I made this form:

<form asp-controller="Scheduling" asp-action="ScheduleBlock" method="post">
        <button formaction="/Scheduling/ScheduleBlock/">Schedule Games</button>

So I need the method, GenerateGameEventsFromSchedule(), to accept the two data properties I pass to the view, ViewData["RangeStart"] and ViewData["RangeEnd"].

So I started to write the controller:

    public async Task<IActionResult> GenerateGameEventsFromSchedule(DateTime start, DateTime end)

        foreach (event in GamingEvents)
            //...do this

        return View();

Obviously it's not finished.

My problem is, how would I pass the list of GamingEvents from my view above, to this new controller so that I can do additional processing on each item in the list?


I am trying to pass some data into my controller using a modal. There are multiple modals on the page and I find that only the data from the first modal is passed, regardless if the data was edited in another.

<div id="mark-reassigned-modal" class="modal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h4 id="myModalLabel">@Employee_Index.MarkReassignedHeading</h4>
            <div class="modal-body">
                <div class="alert alert-warning">
                @Html.EditorFor(m => m.DateTimePicker, new { htmlAttributes = new { name = "DateTimePicker", @style = "width:50%;" } })

                @Html.TextAreaFor(m => m.DispositionNotes, new { cols = "50%", rows = "3" })

            <div class="modal-footer">
                <button type="button" class="btn btn-danger dirtyignore" aria-hidden="true" id="mark-reassigned-submit">@Employee_Index.YesExcuseText</button>
                <a href="#" class="btn btn-link cancel dirtyignore" data-dismiss="modal" aria-hidden="true">@Common.Cancel</a>

<div id="mark-new-shift-modal" class="modal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h4 id="myModalLabel">@Employee_Index.MarkNewShiftHeading</h4>
            <div class="modal-body">
                <div class="alert alert-warning">
                @Html.EditorFor(m => m.DateTimePicker, new { htmlAttributes = new { name = "DateTimePicker", @style = "width:50%;" } })

                @Html.TextAreaFor(m => m.DispositionNotes, new { cols = "50%", rows = "3" })

            <div class="modal-footer">
                <button type="button" class="btn btn-danger dirtyignore" aria-hidden="true" id="mark-new-shift-submit">@Employee_Index.YesExcuseText</button>
                <a href="#" class="btn btn-link cancel dirtyignore" data-dismiss="modal" aria-hidden="true">@Common.Cancel</a>

The js for this looks like:

$(document).on("click", "#mark-new-shift-submit", function () {
    var resultsContainer = $('#results');
        message: '<i class="fa fa-icon fa-spin fa-spinner bigger-230" />'
    var data = $('#Index').serialize();
        type: "POST",
        url: '@Url.Action("MarkNewShift", "Employee")',
        data: data,
        dataType: "html",
        success: function (data) {

When I inspect the #Index id I find that there are multiple results for DateTimePicker, and it is only taking the first one. How can I make the picker global so there is only one result in #Index. This would also have a benefit of letting the user continue where they left off if they decide to use a different option.

I'm using Razor to display a list of model, and the end user can add or remove entries to that list. After clicking a "Remove" button, the view model is kicked back into the Controller Post to remove the list entry and returned to the View via return View(model);. The hidden IDs of each entry, though, seem to have just had the last row deleted and the other displayed rows moved up by one, resulting in data repopulated to an incorrect ID if another item is added to the list.

In other words, if the first RecipientUserID is 14 and the second is 20, deleting the row of 14 first leaves the displayed data for 20, but the View source says the RecipientUserID is 14, and adding another item changes the first row from 20's data to 14 and that data. Is there a way to reload the table and have the hidden field on the same row with its associated other data? Thanks in advance!


<div class="row">
    <div class="col-lg-12">
        <table class="table table-bordered" id="cTable">
                    <th style="display:none"></th>
                    <th class="text-center">Name</th>
                    <th class="text-center">E-mail</th>
                    <th class="text-center">Select</th>
                @if (Model.Recipients.Any())
                    for (var i = 0; i < Model.Recipients.Count; i++)
                            <td style="display:none">@Html.HiddenFor(m => m.Recipients[i].RecipientUserID)</td>
                            <td align="center">@Model.Recipients[i].RecipientName</td>
                            <td align="center">@Model.Recipients[i].RecipientEmail</td>
                            <td align="center">@Html.CheckBoxFor(m => m.Recipients[i].RemoveRecipient)</td>
<div class="row">
    <div class="col-lg-9">
        <button type="submit" id="removeRecipient" class="btn btn-info removeRecipient pull-right" value="Remove Recipient" name="buttonCommand">Remove Selected</button>
    <div class="col-lg-3">


I have a dropdownlist that is being created in aspx and I want to display different textboxes when I select a different item from ddl. I want to apply MaskedEditExtender control on each textbox (the first one to be a decimal with 2 digits before comma and 2 digit after and the second one to be a three digits number), but when I try to make it from aspx it doesnt make anything. I think that I should make it from codebehind, I have tried some different ways but no one worked. I would appriciate if you help me, thank you!

<asp:Panel ID="dynamicFields" runat="server" Visible="False" >
<asp:Label ID="label_valoreTemperatura" runat="server" 
CssClass="genericLabel" Text="Temperatura Rilevata: " 
EnableViewState="False" />
<asp:Label ID="label_pMax" runat="server" CssClass="genericLabel" 
Text="Pressione Sistolica Rilevata: " EnableViewState="False" />
<asp:TextBox ID="valoreTemperatura" DataMode="Float" runat="server" 
CssClass="infragisticsWebNumericEditor" EnableViewState="False" /> 
<asp:TextBox ID="pMax" DataMode="Float" runat="server" 
CssClass="infragisticsWebNumericEditor" EnableViewState="False" />
<asp:RangeValidator ID="valoreTemperaturaRFV" runat="server" 
CssClass="RequiredFieldValidatorStyle" ControlToValidate="valoreTemperatura" 
ValidationGroup="temperatura" EnableViewState="False" 
ErrorMessage="Temperatura non valida" forecolor="Red" minimumvalue="25" 
maximumvalue="42" type="Double" ></asp:RangeValidator>
<asp:RangeValidator ID="pMaxRFV" runat="server" 
CssClass="RequiredFieldValidatorStyle"  ControlToValidate="pMax" 
ValidationGroup="pressioneArteriosa" EnableViewState="False" 
ErrorMessage="Pressione Diastolica non valida" forecolor="Red" 
minimumvalue="10" maximumvalue="300" type="integer" ></asp:RangeValidator>   
<asp:MaskedEditExtender ID="numberFilterMaskedEditExtender" 
TargetControlID="valoreTemperatura"  MaskType="Number"  Enabled="true" 
ErrorTooltipEnabled="True" runat="server" ></asp:MaskedEditExtender>
<asp:MaskedEditExtender ID="sistMaskedEditExtender" TargetControlID="pMax" 
Mask="999" MaskType="None" ErrorTooltipEnabled="True" runat="server"> 

And in Code Behind :

Private Sub addMask()     'This function is been invoked in 
SelectedIndexChanged of ddl

If tipiRilevazione.SelectedIndex = 1    Then    'valoreTemperatura
numberFilterMaskedEditExtender.Mask = "99.99"
Else sistMaskedEditExtender.Mask = "000"    'pMax
End If
End Sub

I changed my controller from homecontroller to ProfileController. Now my view is not showing anything, but when I changed it back from Profilecontroller to homecontroller it works fine again.

I also changed:

 @using(Html.BeginForm("index", "homeController", FormMethod.Post, new { enctype = "multipart/form-data" }))


@using(Html.BeginForm("index", "ProfileController", FormMethod.Post, new { enctype = "multipart/form-data" }))

I have been using chart API for a long time but from today onward it is not working any idea what is wrong with the Google API?

This is the API for generating QR code.


I am trying to render a full page razor which has partial views to a html using the following code.

        public static string RenderViewToString(Controller coreController, string viewName, object model)
        coreController.ViewData.Model = model;

        using (var stringWriter = new StringWriter())
            // Find the partial view by its name and the current controller context.
            var viewResult = ViewEngines.Engines.FindPartialView(coreController.ControllerContext, viewName);

            // Create a view context.
            var viewContext = new ViewContext(coreController.ControllerContext, viewResult.View, coreController.ViewData, coreController.TempData, stringWriter );

            // Render the view using the StringWriter object.
            viewResult.View.Render(viewContext, stringWriter );

            return stringWriter.GetStringBuilder().ToString();

While the actual page is getting rendered without any issues. For some reason the ajax calls inside the partial view within the full page is not executing. The Render method does not seem to be waiting for the ajax to complete its execution. I have tried setting the ajax execution to be synchronous but it does not seem to be working. I know the ajax request itself is executing since the default message is popping up in the resulting html but the thread does not seem to be waiting for the ajax execution to complete so that the actual data in the partial view can be loaded.

Here is a sample ajax code that executes in the partial view

$(document).ready(function() {
    $('#example').DataTable( {
        "ajax": '../ajax/data/arrays.txt'
    } );
} );

Is there a way for me to cause the Render method to wait till all the ajax requests are completed ?

Any help on this would be appreciated.

We have a main form with some basic inputs and a partial view rendered in a Boostrap Modal dialog:

@model CreateDonutVm
    ViewData["Title"] = "Create Donut";

<div id="homer-search-modal" class="modal" role="dialog">
    <div class="modal-dialog modal-lg">
        <div class="modal-content" id="homerSearchModalContent">
            @await Html.PartialAsync("_SearchHomer.cshtml", Model.HomerSearch)

<form asp-controller="Donuts" asp-action="Create">
    <fieldset class="with-legend">
        <legend>Donut Details</legend>
        <div class="form-row align-items-center">
            @Html.LabelFor(m => m.Donut.BoughtBy, "", new {@class = "col-sm-1 col-form-label-sm"})
            <div class="col-sm-2">
                @Html.TextBoxFor(m => m.Donut.BoughtBy, "", new {@class = "form-control form-control-sm"})
    <div class="clearfix">
        @if (!ViewData.ModelState.IsValid)
            <div class="alert alert-danger" role="alert">
                @Html.ValidationSummary(false, "Donut Creation failed. Please correct these errors:")
        <button type="submit" class="btn btn-primary float-right">Save</button>

When the user clicks the 'Save' button, we don't want the validation messages from the partial view being shown (those errors are shown within the modal form).

I've looked far and wide but can't find an example of someone achieving this.

I initially assumed that because the partial view is rendered outside the form that contains the ValidationSummary control, then it MVC wouldn't assess the state of the controls in the partials.

However, looking at ModelState after submitting the main form, MVC is assessing the partial view controls and putting errors in the ModelState.Errors collection for those partial view controls.

Is there a way to get MVC to only assess the controls in the main form and ignore those in the partial views?

I am using django as my backend server, and everytime my user make a transaction using razorpay, i want a webhook to confirm the transaction id . But unfortunately the webhook seems to be triggering my url but no data is found in the request, i tried searching for the data in request.POST and request.FILES but both are empty

I have a simple service which is : 1. Getting All roles in a system 2. Check the role of current selected user 3. Render all roles in a dropdown , selecting current user roles by default

To do that , I have following code:

 public ActionResult Edit(string userId)

            var user = _oAuthUserService.GetUsers()?.Where(u => u.UserId == userId).FirstOrDefault();

            var userRoles = user.Roles; //[Admin,Manager]

            var allRolesFromService = _oAuthUserService.AllRoles.Select(x=>new {
                Id =x.RoleName,
                Name =x.RoleName
            }).ToList(); //All roles in the System [Role1,Role2,Role3,Admin,Manager]

            ViewData["AllRoles"] = new MultiSelectList(allRolesFromService, "Id", "Name", userRoles);

            return View(user);


In view I am doing ,

@Html.ListBox("AllRoles", (MultiSelectList)ViewData["AllRoles"], new { multiple = "multiple" });

But when I navigate to view , none of the items are pre-selected? What am I missing here?

I am trying to connect Azure DevOps in .net core application with following code.

var url = new Uri("https://abcdxyz.visualstudio.com");

var PAT = "XXXXXgdeuxfroaqho4lhtqjdvbagrotypfgfhtuq6w23ie5z3xoq";

VssConnection connection = new VssConnection(url, new VssBasicCredential(string.Empty, PAT)); WorkItemTrackingHttpClient witClient = connection.GetClient();

it builds successfully. However, it throws error as

System.IO.FileNotFoundException: 'Could not load file or assembly 'System.Net.Http.WebRequest, Version=, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'. The system cannot find the file specified.'

I tried to update Nuget package. But still this error occurs.

Could you please let me know how to resolve this? thanks

I have a swagger endpoint which takes a number, then based upon its value I do operation on db making validation before writing in db so that for one value that operation happens once only. But a corner case happened that when running multiple instance of the swagger at same time if i hit that endpoint with same value it writes twice on db.

Any suggestion of using locking here coz it is not multi threaded, but just multiple instance running from different browser/tabs.

From past few days, Whenever I'm clicking on any button in my application some weird file is downloaded and the click of the button does nothing except for downloading this file. Couldn't find the reason why this is happening. Any help would be appreciated.

Below kind of files get downloaded. enter image description here Thanks already for help.

I am working on my vacation project where i want to build a general accounting management web application(like sales,clients CRUD,outstanding etc) in asp.net mvc. Everything is done but only one part is pending which is how can i take input from user for invoice where one invoice has many products. I buildup two model named SALES and SALESITEM as shown in below picture.Here is model class for salesitem and Here is a model class for sales

What i have done i buildup a viewmodel named as invoice and add property of sale and ienumerable.Here is image of invoice viewmodel

my question is how can i get a invoice viwemodel in controller save actionresult with multiple products in it.please guide me for the same. or if same one have a source code where such scenarion is solved please share with me.. or... someone please guide me how invoice is saved into database in this like. Here is link for similar application which i want to build userid and password is "admin".

Thanking you

I Need Full Example How Asp.Net Work With Google Drive API Authentication I enter image description here

    private static readonly string[] scopes = { DriveService.Scope.Drive };
    private static readonly string applicationName = "GoogleExample";

    private static DriveService GetGoogleDriveService()
        UserCredential credential;
        using (var stream = new FileStream("credentials.json", FileMode.Open,FileAccess.Read))
            string credPath = "SavedToken";
            credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
               new FileDataStore(credPath,true)).Result;

        return new DriveService(new BaseClientService.Initializer
            HttpClientInitializer = credential,
            ApplicationName = applicationName ,


I am Working on a Shop page where I want the Dropdownlist show the available Quantity . (Eg: if stock contains 2 items then Dropdownlist contains Items 1 followed by 2..)

Here's the code I attempted , I have no idea in which event i should put it.


connect cu = new connect();

 System.Web.UI.WebControls.Label Label8 = (System.Web.UI.WebControls.Label)DataList1.FindControl("modelnoLabel");

//Modelnolabel contains model no

    cu.cmd.CommandText = "select qty from stock where modelno=@mod";
//qty is retrived based on modelnolabel text of datalist

    cu.cmd.Parameters.AddWithValue("@mod", Label8.Text);
    int qty = Convert.ToInt16(cu.cmd.ExecuteScalar());
    if (qty < 5 && qty > 0)
        (DataList1.FindControl("DropDownList1") as DropDownList).Items.Clear();
        for (int i = 1; i < qty + 1; i++)
            (DataList1.FindControl("DropDownList1") as DropDownList).Items.Add(Convert.ToString(i));
        (DataList1.FindControl("DropDownList1") as DropDownList).Visible = false;


Thanks in advance

I have this scenario where we use model classes to generate an excel file, however due to the new requests it requires to process Dynamic objects that includes the attributes which are necessary to be processed by the excel file code generator.

So if I have model, let's say User:

public class User 
    public string FirstName { get; set; }

    public string LastName { get; set; }

    public string EmailAddress { get; set; }

So if a user does not want to include the EmailAddress field this should be excluded when export engine try to do model.GetType().GetProperties() to process the property name and its value to the excel.

I tried to use the ExpandoObject however it does not work when I try to access the properties through model.GetType().GetProperties() even if I have passed the whole PropertyInfo to the IDictionary<string, object> value.

How do I do this using dynamic? FYI the custom attribute is import to be included as part of the object and it's property because there is a filtering using these attribute to process even further the model class.


This object is a generic IList, for instance it can be IList<User>since it's data export to excel.

I need to add standard asp.net authentication to our webforms application. I expect after successful authentication to be redirected to the default.aspx page, or any page based on the url. For some reason, after calling FormsAuthentication.RedirectFromLoginPage(), I get to the Login.aspx again. Maybe somebody could shed some light on it.

    <asp:TextBox ID="txtUserName" CssClass="form-control username" runat="server" />
    <asp:TextBox ID="txtPassword"  CssClass="form-control password" runat="server" TextMode="Password" />
    <asp:Button ID="btnSubmit" OnClick="Submit_OnClick" Text="Login" CssClass="btn btn-primary" runat="server" />

    If Membership.ValidateUser(txtUserName.Text, txtPassword.Text) Then
        FormsAuthentication.RedirectFromLoginPage(txtUserName.Text, False) 
    End If

    <authentication mode="Forms">
       <forms cookieless="UseCookies" path="/" slidingExpiration="true" enableCrossAppRedirects="true" loginUrl="login.aspx" protection="All" timeout="90" requireSSL="false" />
      <deny users="?" />

I'm using a Gridview to display a download link LinkButton inside of a TemplateField in ASP.NET (webforms). The header of the first column is being displayed in the body of all rows on the second column and I get a Non-table node initialisation error. enter image description here The table displays correctly (without jQuery Datatables styling) when jQuery is removed so I would assume the problem would be in the jQuery used to prepend the headers. However, if I remove the TemplateField, the table displays correctly so that leaves me to think it has something to do with the TemplateField. Here is the aspx page:

    <asp:GridView ID="tblDownload" runat="server" AutoGenerateColumns="false" CssClass="table table-bordered table-striped dataTables_scrollHead" Visible="true">
            <asp:BoundField DataField="FILE_NAME" HeaderText="File Name" />
            <asp:TemplateField HeaderText="Download" SortExpression="Download">
                    <asp:LinkButton ID="ID" runat="server" Text="Download" OnClick="DownloadFile" CommandArgument='<%# Eval("ID") %>'></asp:LinkButton>

and here is the jQuery:

var Table1 = $("[id*=tblDownload]").prepend($("<thead></thead>").append($("[id*=tblDownload] tr:first"))).DataTable({


I've got a little problem saving data from labels so that when the page reloads the data does not go into the void.

Scenario: on the page load some data gets pulled from SQL table and gets displayed in Labels(meaning that data from row[0] will be displayed on page load). On form there are also some radio buttons where the clients makes choices. Now when a client clicks one button data on page load (label text and radio button choices) should be submitted in database and the next row in data table should be displayed. This will continue until the last record in the data table.

Any help will be highly appreciated.

Thanks in advance