When I add a call on viewComponent in a view and the viewComponent not working, there are not error message, the razor view skip the viewComponent in render and show the rest, but I don't no why the viewComponent not working.

In previous version MVC 5, when there are an error in razor view, the exception was throw, how to make the equivalent in aspnet core ?

I have an ASP.NET MVC/WebApi app that I want to be able to reuse via WebApi with a Xamarin app and a UWP app, and maybe even possibly Unity3D in future projects. I'm using the default authentication provided by Visual Studio when you make a MVC/WebApi project in VS2017 that's using AccountController to authenticate.

What is a good way to implement authentication over the WebApi controller so that I can enforce the same authentication across Xamarin/UWP/Unity3D via native controls like textboxes rather than a web interface so that it does not pull up a browser to do the authentication screen that the web side would? Do I need to change anything on the WebApi side or would it all be in the client?

I have some old Web API action method which returns CSV file. It worked for long time, but recently stopped. Now it causes ERR_SPDY_PROTOCOL_ERROR.

ERR_SPDY_PROTOCOL_ERROR in Chrome is often associated with Avast security as described here. In my case however it's not caused by Avast, and other web browsers throw exceptions too.

My action method looks as follows:

[HttpGet]
[Route("csv")]
public HttpResponseMessage SomeMethod([FromUri]SomeSearchCriteria sc)
{
    using (MemoryStream stream = new MemoryStream())
    {
        StreamWriter writer = new StreamWriter(stream, Encoding.UTF8);
        string content = someLogic.SomeSearchmethod(sc);
        writer.Write(content);
        writer.Flush();
        stream.Position = 0;

        HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
        result.Content = new StreamContent(stream);
        result.Content.Headers.ContentType = new MediaTypeHeaderValue("text/csv");
        result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment") { FileName = "Export.csv" };
        return result;
    }              
}

The method is called by angular front end by simple change of window.location on button click.

Whole action method is executed properly, with no exceptions. Error is shown only by web browser.

Flushing sockets in Chrome as described here does not solve the issue.

I have an IIS server version 8.5. I have web site and a number of web-services hosted on this web site. A number of windows services and desktop apps are working this with IIS instance. And everything is ok for some time. But some time later IIS begin to use 100% of cpu resources. I can suppose that my code is the probem, but firstly i'm doing next steps:

  1. I'm switching off all windows services and desktop apps.
  2. Switching off w3wp process from processes.
  3. Restrating several times app pool, iis and site.

But after i'm startig again iis, pool and site and nothing else (nothing is using iis) i can see that iis worker process using about 20% of cpu resources. And the situation above can be repeated again after some time. It means that the problem can't be in the my code.

What can be the problem of the iis high-load then it just started and then it uses 100% of cpu?

I'm currently trying to make a twilio app. Most of the packages have downloaded just fine, however when I attempt to download the "Twilio.Asp.Net.MVC" package it says that it's not compatible with .net framework (1.1). I was wondering what options I had as far as updating the framework, or possibly downgrading the package? I'd like to quickly mention that i'm using a Mac OS.

Thanks in advance!

I am new to ASP.NET. I am trying to display the text of a radio button in a text box when the radio button is selected. I have tried two different ways of doing it without success:

Attempt 1:

Code in my aspx file:

<asp:RadioButtonList ID="radioList" runat="server">
<asp:ListItem Value="selection1" Text ="One"></asp:ListItem>
<asp:ListItem Value="selection2" Text="Two"></asp:ListItem>
</asp:RadioButtonList>

And then my .cs code:

 public void displayText(object sender, EventArgs e)
{
  var result = radioList.SelectedValue;
    output.Text = result.Text; /* Have also tried result.ToString() */
}

Attempt 2:

Same aspx as above

.cs code:

 public void displayText(object sender, EventArgs e)
{
  if (selection1.Checked)
    {
        output.Text = "One";
    }
}

The first attempt doesn't give me any errors, but doesn't display the text. The second attempt gives me Error CS0103 The name 'selection1' does not exist in the current context 1_ASPTEST.aspx

I'm sure it's something simple that I'm just overlooking but I'm stumped. Thanks!

How to filter dropdown list, and i need to take name of logged in User.

in controller i have this code:

    var agentBR = (Session["aID"]);
    ViewBag.AgentID = new SelectList(db.tbl_agenti.Where(x => x.aID.Equals("agentBR")), "aID", "agent_ime");

but not work, session id ok, and in the browser i have this error:

DbComparisonExpression requires arguments with comparable types.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.ArgumentException: DbComparisonExpression requires arguments with comparable types.

Source Error:

@Html.LabelFor(model => model.AgentID, "AgentID", htmlAttributes: new { @class = "control-label col-md-2" })

@Html.DropDownList("AgentID", null, htmlAttributes: new { @class = "form-control" })

@Html.ValidationMessageFor(model => model.AgentID, "", new { @class = "text-danger" })

I am developing ASP.NET Core web api. here i have a situation like i have to use multiple get functions which get data from sql server db. So for that i'm doing custom attribute routes. below are my codes

[Route("api/[controller]")]
public class MeController : Controller
{
    private readonly ITechRepository _tech;
    private readonly IPageOptions _page;
    public MeController(ITechRepository tech,IPageOptions page)
    {
        _tech = tech;
        _page = page;
    }

   [Route("getTech")]
    public IEnumerable<TechStack> Get()
    {
        return _tech.getAll();
    }
    [Route("getOptions")]
    public IEnumerable<PageControl> getOptions()
    {
        return _page.getOptions();
    }
     //GET api/values/5
    [HttpGet("{id}")]
    public int Get(int id)
    {
        return id;
    }
}

The above routes are works well in VS IIS Express and this is that url http://localhost:51889/api/me/gettech

But when i publish this api in IIS 10. The getTech and getOptions were not working it producing 404 error and also [HttpGet("{id}")] is working in both.

Can anybody help on this...

this is my code snippet ,i mtakin src from local folder, when i am loading the page the video src is automatically play and want to stop this .I have lots of thing please heplp me..i m new to HTML5

i have gridview with many col some of col will sum and display in total col using rowdatabound and it works only in view, but the problem when i try to edit using edit statement that gridview have this error appear (Troubleshooting exceptions: system.nullreferenceexception)

 protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        string val1 = e.Row.Cells[13].Text; //Gets the value in Column 1
        string val2 = e.Row.Cells[14].Text; //Gets the value in Column 2
        string val3 = e.Row.Cells[15].Text; //Gets the value in Column 3
        string val4 = e.Row.Cells[16].Text; //Gets the value in Column 4
        Label lblTotal = (Label)e.Row.Cells[12].FindControl("Label1"); //
        float _val1, _val2, _val3, _val4;

        float.TryParse(val1, out _val1);
        float.TryParse(val2, out _val2);
        float.TryParse(val3, out _val3);
        float.TryParse(val4, out _val4);

        float sum = _val1 + _val2 + _val3 + _val4;
        lblTotal.Text += sum.ToString();

    }
}

I am working on a project in which I want to increase the space between the two columns and their respective fields .I also want to align one of my column named as detail to left hand side in a proper manner can any one tell me how to do it.Image in which i want to increase the space Here is my code :

<asp:DetailsView ID="DetailsView1" runat="server" Height="50px" Width="650px" AutoGenerateRows="False"
                        DataSourceID="SqlDataSource2" GridLines="None" Font-Bold="True" Font-Size="Medium">
                        <Fields>
                            <asp:BoundField DataField="categoryname" HeaderText="Category:" SortExpression="categoryname" />
                            <asp:BoundField DataField="subcatname" HeaderText="Subcategory:" SortExpression="subcatname" />
                            <asp:BoundField DataField="packageprice" HeaderText="Price:" SortExpression="packageprice" />
                            <asp:BoundField HeaderText="" DataField="detail" SortExpression="detail">

                            </asp:BoundField>
                        </Fields>
                    </asp:DetailsView>

I have used:

Request.Unvalidated.Form["valuefromcontrol"];

Because my control returns values in tags, i.e (<p> values </p>) etc. but it gives null values.

I have searched about it and found this Asp Unvalidated Input

But when I used the technique that is mentioned in above link it gives error in the given link the description of Unvalidated Method is used as

string var = Request.Unvalidated("valueofcontrol");

and

string var = Request.Unvalidated().Form["valueofcontrol"];

But when I tried to use these technique vs gives an error saying that Unvalidated cannot used as method.

What should I do for getting value without validation ?

for more better understanding I have used CKEDITOR as a control.

I have View where I create interview with greeting and details

Here is table

CREATE TABLE [dbo].[Interviews] (
[Interview_Id] INT            IDENTITY (1, 1) NOT NULL,
[Greeting]     NVARCHAR (MAX) NULL,
[Detail]       NVARCHAR (MAX) NULL,
[VacancyId]    INT            NULL,
PRIMARY KEY CLUSTERED ([Interview_Id] ASC),
CONSTRAINT [FK_Interviews_ToTable] FOREIGN KEY ([VacancyId]) REFERENCES [dbo].[Vacancies] ([VacancyId]) ON DELETE CASCADE

);

Here is my controller for this View

  // Страница ввода приветствия и описания вакансии
    [HttpGet]
    public ActionResult WelcomeScreen()
    {
        // Формируем список команд для передачи в представление
        SelectList teams = new SelectList(db.Vacancy, "VacancyId", "VacancyName");
        ViewBag.Teams = teams;

        return View();
    }


    //Заносим инфу о вакансии в таблицу
    [HttpPost]
    public ActionResult WelcomeScreen(Interview interview)
    {
        db.Interview.Add(interview);
        db.SaveChanges();
        //Int32 id = interview.Interview_Id;
        //TempData["id"] = id;

        return RedirectToAction("Index", "Questions", new { id = interview.Interview_Id });
    }

Here is my View

    @using (Html.BeginForm())
{
    <div class="outer-div">
        <div class="inner-div">
            <div class="right-welcome-div">
                <div class="right-grid-in-grid">

                    <div class="col-md-10">
                        @Html.DropDownListFor(model => model.Vacancy.VacancyId, ViewBag.Teams as SelectList, new { @class = "greeting" })
                        @Html.ValidationMessageFor(model => model.VacancyId, "", new { @class = "text-danger" })
                    </div>

                </div>
                <div class="main-left-div">

                    <div style="margin-left: 40px">
                        @Html.EditorFor(model => model.Greeting, new {htmlAttributes = new {@class = "greeting", data_bind = "textInput: Greeting", placeholder = "Приветствие", id="Greeting"}})
                    </div>

                    @Html.TextAreaFor(model => model.Detail, new { @class = "greeting2", data_bind = "textInput: Detail" })

                </div>
             </div>
            <div class="left-welcome-div">
                <div class="text-div" style="padding-top: 30px; word-break: break-all;">
                    <p style="font-size: 20px; margin-top: 20px; padding-left: 30px; padding-right: 40px; text-align: center;"><b><span data-bind="text: Greeting"/></b>
                    </p>
                    <p style="font-size: 20px; margin-top: 40px; padding-left: 30px; padding-right: 40px; text-align: center;"><span data-bind="text: Detail"/>
                    </p>
                </div>
                <div class="button-div" style="padding-top: 40px;">
                    <input  style="float: right; margin-right: 30px; margin-top: 20px; border-radius: 12px; width: 200px;" type="submit" value="Создать" class="btn btn-default" />
                    </div>
            </div>
        </div>
    </div>
    <script type="text/javascript">
        function ViewModel() {
            this.Greeting = ko.observable('');
            this.Detail = ko.observable('');
        };

        var vm = new ViewModel();
        ko.applyBindings(vm);

    </script>
}

When I click submit button it creates new empty row in Vacancies table.

I don't understand, why??

Why so?

I've read MSDN documentation of JsonRequestBehavior.AllowGet and many answers here at SO. I experimented and I am still confused.

I have the following action method. It works fine if I use POST method in my ajax call. It fails with status 404 (Resource not found) if I use GET method in my ajax call. So, the question is what exactly does the JsonRequestBehavior.AllowGet enum do in this Json method? The MSDN documentation says: AllowGet HTTP GET requests from the client are allowed. (https://msdn.microsoft.com/en-us/library/system.web.mvc.jsonrequestbehavior(v=vs.118).aspx), but then why does it fail when I use GET method in my ajax call? Changing the attribute from HttpPost to HttpGet does not help, it fails with either POST or GET method.

 [HttpPost]
    public JsonResult Create(Model m)
    {
        m.Ssn = "123-45-8999";
        m.FirstName = "Alan";
        m.LastName = "Chang";
        m.Id = 1000;
        return Json(m, JsonRequestBehavior.AllowGet);
    }

    public class Model
    {
       public int Id { get; set; }
       public string Ssn { get; set; }
       public string FirstName { get; set; }
       public string LastName { get; set; }
    }

Here is my jQuery ajax call:

    $(function () {
        console.log("hola");

        $("button").on("click", function () {
            $.ajax({
                method: "POST", //Try changing this to GET and see.
                url: "Home/Create",
                data: { Id: 123, Ssn: "585-78-9981", FirstName: "John", LastName: "Smith" }
            })
    .done(function (msg) {
        alert("Data Saved: " + msg);

        });

  });

    })

In Startup.Auth.cs

app.UseFacebookAuthentication(
   appId: "xxxxxx",
   appSecret: "xxxxxx");

app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions()
{
    ClientId = "ssssss",
    ClientSecret = "sssss"
});

In my localhost both google and facebook external login are working but in my live site facebook is not. In my live site when a user clicks facebook login it will prompt for permission but it will just go back to Login, I think it's returning null

 public async Task<ActionResult> ExternalLoginCallback(string returnUrl)
{
    var loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync();
    if (loginInfo == null)
    {
        return RedirectToAction("Login");
    }

    // Sign in the user with this external login provider if the user already has a login
    var result = await SignInManager.ExternalSignInAsync(loginInfo, isPersistent: false);
    switch (result)
    {
        case SignInStatus.Success:
            return RedirectToLocal(returnUrl);
        case SignInStatus.LockedOut:
            return View("Lockout");
        case SignInStatus.RequiresVerification:
            return RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = false });
        case SignInStatus.Failure:
        default:
            // If the user does not have an account, then prompt the user to create an account
            ViewBag.ReturnUrl = returnUrl;
            ViewBag.LoginProvider = loginInfo.Login.LoginProvider;
            var viewModel = new ExternalLoginConfirmationViewModel
            {
                Email = loginInfo.Email
            };
            ViewBag.Title = "Register";

            return View("ExternalLoginConfirmation", viewModel);
    }
}

Any idea? My live site is not using ssl.

First this is an ASP.net webform project.

I have a pretty simple loop using EntityFrameWork

foreach(student s in classes)
{
    connector.student.Add(s);
}

Here, connector is the object used to access EntityFramework methods. But When tha query executes, I get the following error :

An entity object cannot be referenced by multiple instances of IEntityChangeTracker.

What could be causing that error ?

I read Entity Framework "An entity object cannot be referenced by multiple instances of IEntityChangeTracker"

I made sure connector was the only entityframework object used to perform my CRUD operations. I still get the error. BUT connector is used on the Page_Load event WITHOUT any issue.

ps : I did not post too much code because this is new to me. Let me know if you need to see some more code.

When creating a web method in an ASMX file of a C# web application, the associated WSDL is of this format:

<Envelope>
  <Header/>
  <Body>
    <WebMethodName>
      <WebMethodArgumentName>
        <WebMethodArgumentType>

I need to have it like this:

<Envelope>
  <Header/>
  <Body>
    <WebMethodName>
      <WebMethodArgumentType>

Or like this:

<Envelope>
  <Header/>
  <Body>
    <WebMethodArgumentName>
      <WebMethodArgumentType>

This is because the client sends the request in that format, so I need to control the name of the outer tag, and the only way I can think of is by changing the name of the web method or the web method argument, but in order to do that, I need to have only one of those tags.

How can I accomplish this?

Thanks in advanced, guys!

I'm currently trying to take an ASP.NET Web Forms project written in Visual Studio 2013 on Windows 7 and move it to an IIS 6 site on Windows Server 2008, but I'm having trouble figuring out how to do it.

I've tried simply copying the project file from the Visual Studio directory to the one used by the site, but this causes important navigation commands to not work properly.

I've also tried using Visual Studio's Publish tool, but I haven't been able to get the Web Deploy, Web Deploy Package, FTP, or File System publish methods to work properly. I'm not certain which, if any, of these to use.

If anyone knows a method that could accomplish this, please let me know.

This question already has an answer here:

I'm trying to parse a markdown-string:

My model is something like this:

class Model
{
    public string MethodName {get;set;}
    public string CodeBlock {get;set;}
}

json-data of my model:

{
    "MethodName":"Test",
    "CodeBlock":"int[] s = new List<int>().ToArray();"
}

my template looks like this:

string template = @"# @Model.MethodName

```csharp
@Model.CodeBlock
```";

I'm parsing with:

string generatedCode = Razor.Parse(template, model);

the parsed output now looks like:

# Test

```csharp
int[] s = new List&lt;int&gt;().ToArray();
```

So the engine parses < to &lt; and > to &gt; (instead of leaving it with those brackets), which is not correct displayed in a markdown-editor. What I really want to get is:

# Test

```csharp
int[] s = new List<int>().ToArray();
```

Any idea what I could do to get this?

With Asp.Net it was easy to see the code generated by the Razor View Engine: Add a compile error and the error page will give access to the source of the Razor Page.

This changed with Asp.Net Core, which I read somewhere creates the code in memory and does not allow access to that code easily.

Question: Someone knows a trick how to access generated Razor source code with Asp.Net Core?

I'm building a webapp in ASP.NET and am trying to get a button (a Panel) to load a "window" or sub application to add new users. I want the div holding the buttons to transitionally clear or be "deleted" and in the same window, load the corresponding application/div. Most people suggest Ajax but none of the answers I've found have the desired effect I want. Below is a sample of the button/panel item which is contained in a div that is 100% vh and 100% vw. I'm not exactly familiar with jQuery either which doesn't help.

Thanks in advance.

<div class="admin-panel">
            <div class="row admin-controls">
                <div class="col-md-2"></div>
                <div class="col-md-2">
                    <asp:Panel runat="server" >
                        <div class="admin-control-item" onclick=""><!-- This is the button to load the application -->
                             <i class="material-icons md-48">people</i>
                             <h3>Current Users</h3>
                         </div>
                    </asp:Panel>
                </div>
...
</div>