I'm developing a solution that uses ASP.NET MVC 5, C#, Razor.

Problem:

I have a view that after saving it doesn't view the content of the partial view, I only see the Textbox control for Description field.

View

@Html.HiddenFor(m=>m.Items)
@Html.Partial("~/Areas/Checks/Views/Shared/_ViewerItems.cshtml", Model.Items)

@Html.TextBoxFor(m => m.Description, new { @class = "form-control" })



@{
    var len = Request.RawUrl.Split('/').Count();
    var viewname = Request.RawUrl.Split('/')[len - 1];
    var _newprefixbuttoname = "Salva"+viewname;
    var _newprefixbuttonameProsegui = "Salva" + viewname+"Prosegui";
    //
    if (SessionManager.IsUserConnected(Xanta.ServiceLayer.BO.Ruoli.IsRole411))
    {
        <!-- saving buttons -->
        <div class="form-group">
            <div class="col-md-offset-2 col-md-10 text-right">
                <input type="submit" name="@_newprefixbuttoname" value="Salva" class="btn btn-lg btn-info" />
                <input type="submit" name="@_newprefixbuttonameProsegui" value="Salva e prosegui" class="btn btn-lg btn-success" />
            </div>
        </div>
    }


}

-

-

P.S.: the post method used is the same used in the other views but in this case occurs this problem. Anyway I show it to you

Source

[HttpPost]
[ValidateAntiForgeryToken]
[HttpParamAction]
public ActionResult SaveData(Valutation mv)
{
    return savingDataValutation(mv);
}

private ActionResult savingDataValutation(Valutation mv, bool goon = false)
{
    if (!ModelState.IsValid)
        return View(mv);

    var responseData = manager.savingDataValutation(base.getCurrentCompany(), mv);
    if (responseData.Error)
        ModelState.AddModelError("", responseData.Message);

    if (goon)
        return RedirectToAction(nextpage);

    setSuccessMessage();
    return View(mv);
}

PartialView

@using System.Web.UI.WebControls
@model Xanta.Areas.Checks.ViewModels.ViewerVerificheViewModel
@{
    bool allrespnull = Model.Items.Count() == Model.Items.Count(x => x.RispostaValue == null);
    var dropDownBMMA = new List<ListItem> 
        { 
              new ListItem { Text = "Bassa", Value = "B" }, 
              new ListItem { Text = "Medio Bassa", Value = "MB" } ,
              new ListItem { Text = "Medio Alta", Value = "MA" } ,
              new ListItem { Text = "Alta", Value = "A" } 
        };
}
<style>
    .colrisp{
        width: 100px;
        text-align:center;
    }
    .norisp{
        color:red;
    }
</style>

<table class="table table-bordered table-hover table-striped">
    <tbody>
        @for (int i = 0; i < Model.Items.Count; i++)
        {
            if (Model.Items[i].Visible)
            {
                <tr @{ if (!allrespnull && Model.Items[i].TipoRisposta != 1 && Model.Items[i].TipoRisposta != 6 && Model.Items[i].RispostaValue == null) { <text> class="norisp" </text>         } }>
                    <td>
                        <b>&#8226;</b>
                        @*@Html.DisplayFor(m => m.Items[i].VerificaTesto)*@
                        @Html.Raw(Model.Items[i].VerificaTesto)
                        @Html.HiddenFor(m => m.Items[i].idVerifica)
                        @Html.HiddenFor(m => m.Items[i].VerificaTesto)
                    </td>
                    @if ((Model.Items[i].TipoRisposta == 2) || (Model.Items[i].TipoRisposta == 3) || (Model.Items[i].TipoRisposta == 5))
                    {
                        <td class="colrisp">
                            @Html.Label("Si")
                            @Html.RadioButtonFor(m => m.Items[i].RispostaValue, "S", new { @id = "rbSi" + i.ToString() })
                        </td>
                        <td class="colrisp">
                            @Html.Label("No")
                            @Html.RadioButtonFor(m => m.Items[i].RispostaValue, "N", new { @id = "rbNo" + i.ToString() })
                        </td>
                    }
                    @if (Model.Items[i].TipoRisposta == 3)
                    {
                        <td class="colrisp">
                            @Html.Label("Non pert")
                            @Html.RadioButtonFor(m => m.Items[i].RispostaValue, "NP", new { @id = "rbNP" + i.ToString() })
                        </td>
                    }
                    @if (Model.Items[i].TipoRisposta == 4)
                    {
                        <td class="colrisp">
                            @*@Html.EditorFor(m => m.Items[i].RispostaValue, "NP", new { @id = "txt" + i.ToString(), @class = "form-control" })*@
                            @Html.TextBoxFor(m => m.Items[i].RispostaValue, new { @class = "form-control", @id = "txt" + i.ToString() })
                        </td>
                    }
                    @if (Model.Items[i].TipoRisposta == 5)
                    {
                        <td class="colrisp">
                            @Html.Label("Non valutabile")
                            @Html.RadioButtonFor(m => m.Items[i].RispostaValue, "NV", new { @id = "rbNV" + i.ToString() })
                        </td>
                    }
                    @if (Model.Items[i].TipoRisposta == 7)
                    {
                        <td class="colrisp">
                            @Html.DropDownListFor(m => m.Items[i].RispostaValue, new SelectList(dropDownBMMA, "Value", "Text", Model.Items[i].RispostaValue), "", new { @id = "ddl7_" + i.ToString() })
                        </td>
                    }
                    @if (Model.Items[i].TipoRisposta == 8)
                    {
                        <td class="colrisp">
                            @Html.CheckBoxFor(m => m.Items[i].CheckBoxValue, new { @id = "chk8_" + i.ToString() })
                        </td>
                    }

                </tr>
                if (Model.Items[i].TipoRisposta == 6)
                {
                    <tr>
                        <td class="colrisp">
                            @Html.TextAreaFor(m => m.Items[i].RispostaValue, new { @class = "form-control", @rows = 8, placeholder = @Model.Items[i].PlaceHolder, style = "max-width:100% !important;" })
                        </td>
                    </tr>
                }

            }
        }
    </tbody>
</table>

The partialview works very well in other contexts! But I don't understand what's wrong.

Any suggestions? Thanks

(why you decrease my reputation...I'll have fear next time to write a new post! )

@foreach (var sprd in ViewBag.subProduct)
                       {
                            <div class="form-row control-group row-fluid">
                                <div class="controls span2">
                                    <select id="text" style="visibility: hidden;"></select>
                                </div>
                                <div class="controls span2">
                                    @sprd.subproduct_pricetitle
                                    @Html.Hidden("title1", (string)@sprd.subproduct_pricetitle)
                                </div>
                                @Html.Hidden("subid", (int)@sprd.subproduct_id)
                                <div class="controls span2">
                                    <div class="input-prepend input-append row-fluid">
                                        <span class="add-on prepend ">&pound; </span>
                                        @Html.TextBox("combined-input1", (decimal)@sprd.subproduct_price, new { @class = "row-fluid" })
                                    </div>
                                </div>
                            </div>
                        }

This is a code for displaying the data on view page.

 public ActionResult Update(int id)
    {
        IEnumerable<producttype_master> Product_Typee;
        int producttypeid = Convert.ToInt32(context.product_master.Find(id).product_type.ToString());
        Product_Typee = context.producttype_master.ToList();
        ViewBag.productType = new SelectList(Product_Typee, "producttype_id", "producttype_name", producttypeid);

        IEnumerable<product_master> products;
        products = context.product_master.ToList();
        //List<subproduct_master> sprdList = context.subproduct_master.Where(m => m.product_id == id).ToList();
        IEnumerable<subproduct_master> sprdList = context.subproduct_master.Where(m => m.product_id == id).ToList();
        ViewBag.subProduct = sprdList;

        return View(context.product_master.Find(id));
    }

This update code is not working well, giving error. [HttpPost] public ActionResult Update(product_master prdmaster, subproduct_master subprdmaster, FormCollection formCollection) {

        product_master prd = context.product_master.Where(m => m.product_id == prdmaster.product_id).FirstOrDefault();
        if (prd != null)
        {
            prd.product_type = int.Parse(formCollection["PrdType"]);
            prd.product_updateby = 1;
            prd.product_updateon = DateTime.Now;
            prd.product_isactive = "1";

            subproduct_master sprdList = context.subproduct_master.Where(m => m.product_id == prd.product_id).FirstOrDefault();
           if (sprdList != null)
            {

                //string latestId = context.product_master.Max(p => p.product_id).ToString();

                for (int i = 1; i <= 7; i++)
                { 
                    subproduct_master sprdList2 = context.subproduct_master.Where(m => m.subproduct_id == sprdList.subproduct_id).FirstOrDefault();
                    sprdList2.subproduct_price = decimal.Parse(formCollection["combined-input" + i]);
                    sprdList2.subproduct_pricevalidity = Convert.ToDateTime(formCollection["datepicker1"]);
                    sprdList2.subproduct_updatedon = DateTime.Now;
                    sprdList2.subproduct_updatedby = 1;
                    sprdList2.subproduct_isactive = "1";
                    context.Entry(sprdList2).CurrentValues.SetValues(sprdList);
                    //context.SaveChanges();
                    sprdList2.subproduct_id++;
                }

            }
           context.Entry(prd).CurrentValues.SetValues(prdmaster);
           context.SaveChanges();

      }
        return View(prdmaster);
        }

I have two footable paginations on one page. They are auto-generated by the footable.pagniate.js. That's the code, where they are generated:

<div class="pagination pagination-centered"></div>


<div class="table-responsive" style="background-color: #fff;">
        <table class="table table-hover border-time footable2 toggle-arrow-small time-green" data-filter="#filter-customers" data-page-size="15" style="margin-bottom:0px;" id="table-customers">
            <thead>
                <tr>

                    <th data-toggle="true" data-sort-initial="true" class="floatLeft ex1">Ex1</th>
                    <th class="floatLeft ex2">Ex2</th>
                    <th class="floatLeft ex3" data-hide="phone,tablet">ex3</th>
                    <th class="floatLeft ex4" data-hide="phone,tablet" data-sort-ignore="true" data-name="ex">Ex4</th>
                    <th class="floatLeft ex5" data-hide="phone,tablet" data-sort-ignore="true">&nbsp; </th>
                    <th class="floatLeft ex6" data-sort-ignore="true">&nbsp; </th>
                </tr>
            </thead>
            <tbody>
                @foreach (var customer in Model.Customers.OrderBy(j => j.Name))
                {

                foreach (var project in customer.Projects.OrderBy(s => s.Name))
                {
                    string projectNameWithOutSpace = project.Name.Replace(" ", "");
                    string projectName = projectNameWithOutSpace.Replace("/", "");



                    <tr class="panel-heading" data-toggle="collapse" data-parent="#accordion" data-target="#@projectName" style="border-bottom: 1px solid #eee;">
                        <td colspan="8">

                            <div class="row" style="margin: 0!important;">
                                <div style="width: 100%">
                                    <div class="floatLeft b4">@customer</div>
                                    <div class="floatLeft b3 ">@project</div>
                                    <div class="floatLeft b1 pc" style="float: left; width: 15%" ;><span class="badge badge-time" style="text-align:center;">@project.Count</span></div>
                                    <div class="floatLeft b2 pc" style="float: left; width: 10%" ;><span class="label label-success label-time pull-right" style="margin-top: 3px;"><a href="#" style="color: #fff;font-weight: bold;"><span></span>ICAL</a></span></div>
                                    <div class="floatLeft b4 pc" style="float: left; width: 5%" ;></div>
                                    <div class="floatLeft b5"><a href="#" class="btn pull-right"><span class="glyphicon glyphicon-chevron-right"></span></a></div>
                                </div>
                            </div>

                            <div id="@projectName" class="panel-collapse collapse">
                                <div class="panel-body" style="border-top: 0px; border-bottom: 1px solid #eee; padding: 0px;">
                                    <div class="table-responsive">
                                        <table class="table table-hover border-time footable2 toggle-arrow-small time-green" data-filter="#filter-services" data-page-size="15" style="margin-bottom:0px;" id="table-services">
                                            <thead>
                                                <tr>
                                                    <th>#</th>
                                                    <th data-sort-initial="true">Drive</th>
                                                    <th>Budget</th>
                                                    <th style="text-align: center;">Time</th>
                                                    <th style="text-align: center;">Drive</th>
                                                    <th style="text-align: center;">Time</th>
                                                    <th style="text-align: center;">Travel</th>
                                                </tr>
                                            </thead>
                                            <tbody>

                                                @foreach (var item in project.Services)
                                                {
                                                    <tr>
                                                        <td>@item.Nr</td>
                                                        <td>@item.Name</td>
                                                        <td>@Html._FormatHours(item.Budget.TotalHours, item.BudgetFactor.TotalHours)</td>
                                                        <td style="text-align: center;"></td>
                                                        <td style="text-align: center;"></td>
                                                        <td style="text-align: center;"></td>
                                                        <td style="text-align: right;">
                                                            <!-- <a href="#" class="btn pull-right"><span class="glyphicon glyphicon-chevron-right"></span></a>-->
                                                        </td>
                                                    </tr>

                                                }

                                            </tbody>
                                            <tfoot class="hide-if-no-paging">
                                                <tr>
                                                    <td colspan="7">
                                                        <div class="pagination pagination-centered"></div>
                                                    </td>
                                                </tr>
                                            </tfoot>
                                        </table>
                                    </div>
                                </div>
                            </div>
                        </td>
                    </tr>
                    }
                }
            </tbody>
            <tfoot class="hide-if-no-paging">
                <tr>
                    <td colspan="7">
                        <div class="pagination pagination-centered"></div>
                    </td>
                </tr>
            </tfoot>
        </table>
    </div>

The most important part of the code is the <div class="pagination pagination-centered"></div>

So, when i click on the arrows (>>) at the first pagination, the second pagination will change the page. So they are both connected. Do you know, how to separate those two?

enter image description here

I have Asp.net MVC 5 project. I want to write a complete test method with unit test for my AccountController methods for exampel :

public async Task Register(RegisterViewModel model) { if (ModelState.IsValid) { var user = new ApplicationUser() { UserName = model.Email }; user.Email = model.Email; user.EmailConfirmed = false; var result = await UserManager.CreateAsync(user, model.Password); if (result.Succeeded) { System.Net.Mail.MailMessage m = new System.Net.Mail.MailMessage( new System.Net.Mail.MailAddress("heidari@webit.de", "LIEKWOE"), new System.Net.Mail.MailAddress(user.Email)); m.Subject = "Email confirmation"; m.Body = string.Format("Dear {0}
Thank you for your registration, please click on the below link to complete your registration:{1}", user.UserName, Url.Action("ConfirmEmail", "Account", new { Token = user.Id, Email = user.Email }, Request.Url.Scheme)); m.IsBodyHtml = true; System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient("mail.webit.de"); smtp.Credentials = new System.Net.NetworkCredential("heidari@webit.de", "Sei0ooYeeth2omoo"); smtp.EnableSsl = true; smtp.Send(m); return RedirectToAction("Confirm", "Account", new { Email = user.Email }); } else { AddErrors(result); } } // If we got this far, something failed, redisplay form return View(model); },

anyone can help me?

I am using wcf service where i have to access wcf service method and show the returned json data in the browser itself. Currently i tried string method so json data is showing as json string format which is incorrect. I have gone through this link and tried with my code but not getting any data because of complete data is in one list.

Below is the interface IService code:

[ServiceContract]
    public interface IService1
    {

        [OperationContract]
        List<SuccessStoryApp> GetSuccessStoryJson();
        [OperationContract]
        [WebInvoke(Method = "GET",
           RequestFormat = WebMessageFormat.Json,
           ResponseFormat = WebMessageFormat.Json,
           UriTemplate = "/GetBlogList/")]
        string GetBlogList();
    }

Service1.svc Code:

 public string GetBlogList()
        {
            log.Info("GetBlostList method entered");
            List<SuccessStoryApp> storyList = new List<SuccessStoryApp>();
            string jsonString = string.Empty;
            var jsonData = GetSuccessStoryJson();
            storyList = jsonData.Select(x => new SuccessStoryApp
            {
                Author = x.Author,
                AuthorSlug = x.AuthorSlug,
                Available = x.Available,
                Category = x.Category,
                CountryCode = x.CountryCode,
                Description = x.Description,
                LanguageCode = x.LanguageCode,
                PublishedDate = x.PublishedDate,
                Quote = x.Quote,
                ShortDescription = x.ShortDescription,
                StoryImageAlt = x.StoryImageAlt,
                StoryImageTitle = x.StoryImageTitle,
                StoryImageURL = x.StoryImageURL,
                Tags = x.Tags,
                Text = x.Tags,
                Title = x.Title,
                TitleImageURL = x.TitleImageURL,
                Type = x.Type
            }).ToList();
            if (storyList.Count > 0)
            {
                var json = JsonConvert.SerializeObject(storyList);
                jsonString = json;
            }
            else
            {
                jsonString = "Some error occurred";
            }
            return jsonString;
        }
and below is my web.config service configuration:

<system.serviceModel>
    <services>
      <service behaviorConfiguration="Default" name="BlogService.Service1">
        <endpoint address="" behaviorConfiguration="webBehavior" binding="webHttpBinding" contract="BlogService.IService1" bindingConfiguration="WHB" />
       
        <host>
          <baseAddresses>
            <add baseAddress="http://localhost:60500/Service1.svc" />
          </baseAddresses>
        </host>
      </service>
    </services>
    <behaviors>
      <endpointBehaviors>
        <behavior name="webBehavior">
          <webHttp  defaultOutgoingResponseFormat="Json" />
        </behavior>
      </endpointBehaviors>
      <serviceBehaviors>
        <behavior>
          <!-- To avoid disclosing metadata information, set the values below to false before deployment -->
          <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/>
          <!-- To receive exception details in faults for debugging purposes, set the value below to true.  Set to false before deployment to avoid disclosing exception information -->
          <serviceDebug includeExceptionDetailInFaults="false"/>
        </behavior>
        <behavior name="Default">
          <serviceMetadata httpGetEnabled="true"/>
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <bindings>
      <webHttpBinding>
        <binding name="WHB" crossDomainScriptAccessEnabled="true">
          <security mode="None" />
        </binding>
      </webHttpBinding>
    </bindings>
    <protocolMapping>
        <add binding="basicHttpsBinding" scheme="https"/>
    </protocolMapping>    
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true"/>
  </system.serviceModel>
I am able to debug GetBlogList method and it is returning currently json string. I wanted to return here original json format.

View

@model List<Dal.IAdministrator>

@Html.Partial("PartialCreateAdmin", new ViewModels.AdministratorCreateModel())

Partial

@model ViewModels.AdministratorCreateModel

@using (Html.BeginForm("Insert", "Admin", FormMethod.Post, new { }))
{
    <fieldset>
        <br />
        @Html.TextBoxFor(m => m.AccountName, new { placeholder = "Enter the account name here" })
        @if (!ViewData.ModelState.IsValid)
        {
            <p style="color: darkblue;"> @ViewData.ModelState["AccountName"].Errors[0].ErrorMessage </p> 
        }
    </fieldset>
    <br />

    <input type='Submit' value='Create' />
}

Controller:

    [HttpPost]
    public ActionResult Insert(AdministratorCreateModel vm)
    {
       // ...
        if(!accountNameExists)
        {
            ModelState.AddModelError("AccountName", "Account name does not exist, please try again!");
            return PartialView("PartialCreateAdmin", vm);
        }
        // ...
    }

Currently If the validation fails, it returns to the partial, but I want to return the view, with the message along the form? How can I do this?

Although there are several questions and answers about the "Unrecognized attribute ‘targetframework’" error, the other questions mainly have to do with errors deploying to a server, and so the answers show IIS 7 settings that need changing. In my case, I was getting the "Unrecognized attribute ‘targetframework’" error when trying to debug in Visual Studio.

I manually modified my web.config file to upgrade it to 4.0, as described in this MSDN article. That included adding the targetFramework attribute to my compilation tag, like this:

    <compilation debug="true" targetFramework="4.0">

I did this because I wanted to use an assembly that targeted the 4.0 framework. But then when I tried to debug the site, I received the "Unrecognized attribute ‘targetframework’" error. As I mentioned, the solutions that I found all talked about changing the application pool in IIS 7, but I was just trying to run the site in the Visual Studio debugger. I tried looking at the Properties for the Solution, but didn't find anything about the framework.

I developed a simple web application on my localhost successfully. The next step is to port over to a remote server. IIS Manager has been configured and a virtual directory has been set. I have copied 2 files over, the page VB and .aspx file.

On the top of the aspx file, I have <%@ Page Language="VB" AutoEventWireup="false" CodeFile="ASPWiki.aspx.vb" Inherits="ASPWiki" %>'. When I try to run, it shows file not found.

When i changed it to <%@ Page Language="VB" AutoEventWireup="false"%>, the page can be displayed but the asp controls cannot be bind as the mysql coding is at my vb file. Any advice on what is the issue?

The error only happened after the files were placed in the server.

I am trying to copy a row from a gridview to be displayed on a new page through a button in one of the columns in the gridview. I have my gridview populated from an Access database that is linked to my project. I have tried several different things, but nothing will display the row information when the project is ran. The current code I am trying from the actual dataview is:

Example 1a

<asp:GridView ID="Grid1" runat="server" Width ="90%" AutoGenerateColumns="false" OnRowDeleting="Grid1_RowDeleting" DataKeyNames="Title">
    <Columns>
        <asp:BoundField DataField="Title" HeaderText="Title" />
        <asp:BoundField DataField="Console" HeaderText="Console" />
        <asp:BoundField DataField="Year_Released" HeaderText="Year Released" />
        <asp:BoundField DataField="ESRB" HeaderText="ESRB Rating" />
        <asp:BoundField DataField="Score" HeaderText="Personal Score" />
        <asp:BoundField DataField="Publisher" HeaderText="Publisher" />
        <asp:BoundField DataField="Developer" HeaderText="Developer" />
        <asp:BoundField DataField="Genre" HeaderText="Genre" />
        <asp:BoundField DataField="Purchase" HeaderText="Purchase Date" />
        <asp:TemplateField ItemStyle-Width="7%" ShowHeader="False">
           <ItemTemplate>
             <asp:LinkButton ID="lnkDetails" runat="server" Text="View" PostBackUrl='<%# "~/ViewDetails.aspx?RowIndex=" & Container.DataItemIndex %>'/>
           </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>

And the codebehind code on the page where I am trying to have the code be displayed is:

Example 1b

 Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
        If Me.Page.PreviousPage IsNot Nothing Then
            Dim rowIndex As Integer = Integer.Parse(Request.QueryString("RowIndex"))
            Dim GridView1 As GridView = DirectCast(Me.Page.PreviousPage.FindControl("Grid1"), GridView)
            Dim row As GridViewRow = GridView1.Rows(rowIndex)
            lblTitle.Text = row.Cells(0).Text
            lblConsole.Text = row.Cells(1).Text
            lblYear.Text = row.Cells(2).Text
            lblESRB.Text = row.Cells(3).Text
            lblScore.Text = row.Cells(4).Text
            lblPublisher.Text = row.Cells(5).Text
            lblDeveloper.Text = row.Cells(6).Text
            lblGenre.Text = row.Cells(7).Text
            lblPurchase.Text = row.Cells(8).Text

        End If
    End Sub

I have also tried another set of code where the button on the gridview was:

Example 2a

<asp:Button ID="btnLink" runat="server" Text="View Details" PostBackUrl='<%# Eval("Title", "~/ViewDetails.aspx?Id={0}") %>'/>

Where the codebehind code is:

Example 2b

    Protected Sub Page_Load(sender As Object, e As EventArgs)
        If Not IsPostBack Then
            Dim GameTitle As String = Request.QueryString("Id")

            Dim connString As String = "PROVIDER=Microsoft.ACE.OLEDB.12.0;" + "DATA SOURCE=" + Path.Combine(AppDomain.CurrentDomain.BaseDirectory + "App_Data" + "db1.accdb")
            Using connection As New OleDbConnection(connString)
                connection.Open()
                Dim reader As OleDbDataReader = Nothing
                Dim command As New OleDbCommand((Convert.ToString("SELECT * from [Video_Games] WHERE Title='") & GameTitle) + "'", connection)
                reader = command.ExecuteReader()
                While reader.Read()
                    lblTitle.Text = reader(0).ToString()
                    lblConsole.Text = reader(1).ToString()
                    lblYear.Text = reader(2).ToString()
                    lblESRB.Text = reader(3).ToString()
                    lblScore.Text = reader(4).ToString()
                    lblPublisher.Text = reader(5).ToString()
                    lblDeveloper.Text = reader(6).ToString()
                    lblGenre.Text = reader(7).ToString()
                    lblPurchase.Text = Convert.ToDateTime(reader(8).ToString()).ToShortDateString()
                End While
            End Using
        End If
    End Sub
End Class

I have tried making variations of both, mainly the second, but whatever I try the labels are not populated with the row information. Any assistance would be appreciated, and I can post any other code needed, like how I populated the gridview. Thank you.

In my javascript file, I got an ajax to get all list and iterate these data and append <a id='userID' class='btn'>Assign ID<> to my list.

So, how do a add postback to these anchor and redirect it inside my method in the server. Below is my code but didn't work. When I click the achor button, it just redirect/refresh to the same page without doing any changes and didn't show the text.

<a id='uniqueID' class='btn assignID' href='javascript:void(0);' onclick='javascript:__doPostBack('uniqueID','')'>Assign ID</a>

protected void Action_assignID(object sender, EventArgs e)
{
  // assign ID action
  Response.Write("Pass");
}

I have read that SqlMembershipProvider doesn't work with SQL Azure, but I am currently using it. I initially encountered some issues, but I am able to login to the site and access role information.

So what is the deal? Do only certain parts of SqlMembershipProvider not work with SQL Azure?

I am using asp.net mvc 5 site for few different domains. Like testsite.com and mysite.com. And because it have different domain in Startup.Auth.cs I need setup different accounts. How can I do that for each domain?

    public void ConfigureAuth(IAppBuilder app)
    {
        ......
        // google account for testsite.com
        app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions()
        {               
            ClientId = "xxxxxxxxxxxxxxxxxxxxxx",
            ClientSecret = "xxxxxxxxxxxx"
        });

        // google account for mysite.com?

    }

Or how I can change those settings in runtime based on site url?

Thanks!

Duke

When I try to build my solution for my MVC project I get the error:

Cannot convert from 'test.Models.User' to 'test.Models.ApplicationUser'

This is is my class User:

    public class User
{
    public int UserId { get; set; }
    [DataType(DataType.Text)]
    public string Name { get; set; }
    [DataType(DataType.PhoneNumber)]
    public string PhoneNumber { get; set; }
    [DataType(DataType.EmailAddress)]
    public string Email { get; set; }
 }

And this is my class UsersController:

  public class UsersController : Controller
{
    private ApplicationDbContext db = new ApplicationDbContext();

    // GET: Users
    public ActionResult Index()
    {
        return View(db.Users.ToList()); //Here
    }

    // GET: Users/Details/5
    public ActionResult Details(int? id)
    {
        if (id == null)
        {
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }
        User user = db.Users.Find(id); //Here
        if (user == null)
        {
            return HttpNotFound();
        }
        return View(user);
    }

    // GET: Users/Create
    public ActionResult Create()
    {
        return View();
    }

    // POST: Users/Create
    // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
    // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create([Bind(Include = "UserId,Name,PhoneNumber,Email")] User user)
    {
        if (ModelState.IsValid)
        {
            db.Users.Add(user); //Here
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        return View(user);
    }

    // GET: Users/Edit/5
    public ActionResult Edit(int? id)
    {
        if (id == null)
        {
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }
        User user = db.Users.Find(id); //Here
        if (user == null)
        {
            return HttpNotFound();
        }
        return View(user);
    }

    // POST: Users/Edit/5
    // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
    // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Edit([Bind(Include = "UserId,Name,PhoneNumber,Email")] User user)
    {
        if (ModelState.IsValid)
        {
            db.Entry(user).State = EntityState.Modified;
            db.SaveChanges();
            return RedirectToAction("Index");
        }
        return View(user);
    }

    // GET: Users/Delete/5
    public ActionResult Delete(int? id)
    {
        if (id == null)
        {
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }
        User user = db.Users.Find(id); //Here
        if (user == null)
        {
            return HttpNotFound();
        }
        return View(user);
    }

    // POST: Users/Delete/5
    [HttpPost, ActionName("Delete")]
    [ValidateAntiForgeryToken]
    public ActionResult DeleteConfirmed(int id)
    {
        User user = db.Users.Find(id); //Here
        db.Users.Remove(user);
        db.SaveChanges();
        return RedirectToAction("Index");
    }

    protected override void Dispose(bool disposing)
    {
        if (disposing)
        {
            db.Dispose();
        }
        base.Dispose(disposing);
    }
}

The extension: enter image description here

This is the view for index (User):

    @model IEnumerable<BowlingBookingSys.Models.User>

    @{
    ViewBag.Title = "Index";
}

<h2>Index</h2>

<p>
    @Html.ActionLink("Create New", "Create")
</p>
<table class="table">
    <tr>
        <th>
            @Html.DisplayNameFor(model => model.Name)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.PhoneNumber)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.Email)
        </th>
        <th></th>
    </tr>

@foreach (var item in Model) {
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.Name)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.PhoneNumber)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Email)
        </td>
        <td>
            @Html.ActionLink("Edit", "Edit", new { id=item.UserId }) |
            @Html.ActionLink("Details", "Details", new { id=item.UserId }) |
            @Html.ActionLink("Delete", "Delete", new { id=item.UserId })
        </td>
    </tr>
}

</table>

I want to add a item in a List from JS script

ViewModel Property:

public ICollection<Channel> Channels { get; set; } = new List<Channel>();

Javascript:

 @Model.Channels.Add(new Channel{ Name = "123" });

I'm using MS Identity and when I'm using a reset token to reset the password, I get this exception:

Inner Exception Type: System.Security.Cryptography.CryptographicException Inner Exception: The data protection operation was unsuccessful. This may have been caused by not having the user profile loaded for the current thread's user context, which may be the case when the thread is impersonating.

This is what the code looks:

var TheProvider = new DpapiDataProtectionProvider("Sample");
UserManager<IdentityUser> TheUserManager = new UserManager<IdentityUser>(new UserStore<IdentityUser>());
TheUserManager.UserTokenProvider = new DataProtectorTokenProvider<IdentityUser>(TheProvider.Create("EmailConfirmation"));

string TheResetCode = TheUserManager.GeneratePasswordResetToken(TheUserMembershiptID);

IdentityResult TheResult = TheUserManager.ResetPassword(TheUserMembershiptID, TheResetCode, TheNewPassword);

I've looked around but I haven't found a solution. What do I need to change to make it work?

Thanks.

i have a textbox.
when i type something i will call function Enter() by onKeyup event.
when i paste that i will call function Paste() by paste event that i bind.
there is the example:
1. create a textbox

<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>

2. setting the keyup event, and bind 'paste' event by jquery

$('TextBox1').keyup(function (event) { Enter(event); }).bind('paste', function (event) { Paste(event); };

3. assume the Enter() and Paste() will alert different message

function Enter(e) { alert(e.which); }
function Paste(e) { alert(e.clipboardData.getData('Text')) };

4. when i typing anything, it will alert and show keycode. 5. when i paste something, it will alert twice, one is show keycode, one is show paste info

I hope when i paste, just only triggered Paste event once, doesn't triggered Enter event.
please teach me how to do. thanks.

I get date from my model and it is displayed in view

@Html.DisplayFor(modelItem => item.UpdateDate)

UpdateDate is datetime.(Format 2017-01-12 17:16:32.013)

What I want to do is, compare it with current date and show difference in time.

  • If the difference between current datetime and UpdatedDate is less than 60 min then it should say "'X' Minues ago" (where 'X' is difference in minutes)

  • If the difference between current datetime and UpdatedDate is more than 60 min and less than 24 hours then it should say " 'Y' Hours 'X' Minues ago" (where 'X' is difference in minutes and 'Y' is hours)

  • If the difference between current datetime and UpdatedDate is more than 24 hours then it should say " 'Z' days 'Y' Hours 'X' Minues ago" (where 'X' is difference in minutes and 'Y' is hours and 'Z' is days)

I want to do this in view. Your help is really appreciated.

Thanks

Hey all new to the MVC world so I'm sure I am not doing something correct here. I am trying to call a function from the model page from my view index page to populate some tooltips.

In my model:

public class tips
{
    public List<string> allTips()
    {
        List<string> theTips = new List<string>();

        theTips.Add("example 1");
        theTips.Add("example 2");

        return theTips;
    }

    private List<string> _tips;
    public List<string> getTips { get { return _tips; } set { _tips = allTips(); } }
}

And in my view:

public ActionResult Index()
{
    var blah = new tips().getTips;

    ViewBag.pageTips = blah;

    return getMainData();
}

And then I have this on the razor page:

@Html.Raw(ViewBag.pageTips[1])

Which should display example 2 on the page but instead it just displays null as the value for the toolTips.

Currently it has a value of null when it gets to the return for the pageTips in my view.

So what would I be doing incorrectly? I put some stops here and there and notice that it never calls the allTips() function so that's a good starting place as to what I need to do in order to do that.

I just figured that calling the .getTips would fire off the theTips function?

This question already has an answer here:

we are sending POST with JSON object like:

{
   "ListId": "1",
   "Items": [
    {
        "EmailAddress": "awesomeemail@awesome.com",
        "PhoneNumber": "sample string 2",
        "FirstName": "sample string 3",
        "LastName": "sample string 4",
        "Gender": 0,
        "Industry": "sample string 6",
        "ItemFieldValues": [
            {
                "TextValue": "sample string 1",
                "NumberValue": 2,
                "MoneyValue": 3.0,
                "YesNoValue": true,
                "DateValue": "2017-01-12T11:47:52.0699749+02:00",
                "ItemFieldId": 5
            },
        ]      
    },
    ]
}

When Items are around 30 000 or less, the controller is hit and the JSON is parsed by the model binder successfully. When I try to send 50 000 the IIS returns "404 not found". Not even Application_BeginRequest is fired in the Global.asax. I have tried to add these lines to the web config file.

<jsonSerialization maxJsonLength="50000000"></jsonSerialization>

and

<httpRuntime executionTimeout="2147483647" maxRequestLength="2147483647" />

and

<add key="aspnet:MaxJsonDeserializerMembers" value="2147483647" />

We need to be able to POST millions of Items in one request. I have Test Console application which generates the json and send it to the server via custom WebClient(no timeout problem) all on localhost env. I think the problem is with the Http Buffer, but can't come up with or find solution. Any suggestions?

pcloud direct download links are unique & only works for ip address which generated it.

so this links can't be share & also don't work in remote upload of any files hosting service.

I searched google last whole night it didn't help me.

My friend told me try fiddler or use WebRequest to solve this problem. But none helped me.

I have below mark-up code in my ASPX page.

        <asp:Repeater ID="rep" runat="server">
            <ItemTemplate>
                <asp:GridView ID="grdVw" runat="server" AutoGenerateColumns="true">
                </asp:GridView>
            </ItemTemplate>
        </asp:Repeater>

Below C# code in my ASPX.CS page

    protected void Page_Load(object sender, EventArgs e)
    {
        DataSet ds = new DataSet();

        for (int i = 0; i < 5; i++)
        {
            ds.Tables.Add(getDT());
        }

        rep.DataSource = ds.Tables;
        rep.DataBind();
    }


    private DataTable getDT()
    {
        DataTable dt = new DataTable();
        dt.Columns.Add("One");
        dt.Columns.Add("Two");
        dt.Columns.Add("Three");

        var row = dt.NewRow();
        row["One"] = "Value1";
        row["Two"] = "Value2";
        row["Three"] = "Value3";
        dt.Rows.Add(row);

        return dt;
    }

My intention is to have multiple gridviews depends on the number of tables of my dataset. After I run this code, I see nothing on the page. I don't know what wrong am I doing here?