Quantcast
Channel: ASP.NET Core
Viewing all 9386 articles
Browse latest View live

asp.net core and entity Framework Core with .net core 2

$
0
0

Hi,

I am currently working on a solution that uses asp.net core (.net 4.6.1) which references entity framework core. After the announcement of microsoft that it will drop support for .net core 1.x on .net core 2.0 I am confused.

Shall I continue using the above or switch back to EF 6?

Thanks


What minimum is required to run asp.net.core web application on a simple windows 7 machine.

$
0
0

Sir

I want to deploy an asp.net.core web application on some system where nothing is installed like visual studio  etc .

What minimum is required to run asp.net.core web application on a simple windows 7 machine.

Actually I want to ask how to deploy asp.net.core web application on some windows 7 machine on which server at least to install on that machine.

Regards

System.MissingMethodException occurred

$
0
0

Hi All,

I got below exception now,  am not sure which missed over my code, it has been working good before.

System.MissingMethodException occurred
HResult=0x80131513
Message=Method not found: 'System.IServiceProvider Microsoft.Extensions.DependencyInjection.ServiceCollectionContainerBuilderExtensions.BuildServiceProvider(Microsoft.Extensions.DependencyInjection.IServiceCollection)'.
Source=Microsoft.AspNetCore.Hosting
StackTrace:
at Microsoft.AspNetCore.Hosting.WebHostBuilder.Build()
at ParticleTrack.Web.Program.Main(String[] args) in file path...

How to populate inputs in "edit" view with object data?

$
0
0

I am quite new to ASP .Net, and could use some help... I have an ASP .Net Core 1.1 MVC web app. In it, I have an "Edit" view for editing a simple object, which is bound to a model, which a corresponding controller calls when routed to it.

This is the view:

@modelInspectionsTestClient.Models.Property@{ViewData["Title"] ="Edit";}<h2>Edit</h2>@Html.ValidationSummary();<form asp-action="Edit"><div class="form-horizontal"><h4>Property</h4><hr /><div asp-validation-summary="ModelOnly" class="text-danger"></div><input type="hidden" asp-for="Id" /><div class="form-group"><label asp-for="UnitNumber" class="col-md-2 control-label"></label><div class="col-md-10"><input asp-for="UnitNumber" class="form-control" /><span asp-validation-for="UnitNumber" class="text-danger"></span></div></div><div class="form-group"><label asp-for="BuildingName" class="col-md-2 control-label"></label><div class="col-md-10"><input asp-for="BuildingName" class="form-control" /><span asp-validation-for="BuildingName" class="text-danger"></span></div></div><div class="form-group"><label asp-for="Street" class="col-md-2 control-label"></label><div class="col-md-10"><input asp-for="Street" class="form-control" /><span asp-validation-for="Street" class="text-danger"></span></div></div></div></form><div><a asp-action="Index">Back to List</a></div>@sectionScripts{@{await Html.RenderPartialAsync("_ValidationScriptsPartial");}}

This is the controller which calls that view:

// GET: Property/Edit/5publicActionResultEdit(int id){returnView();}

And this is the model:

namespaceInspectionsTestClient.Models{//[Table("property")]publicclassProperty{[Key][DatabaseGenerated(DatabaseGeneratedOption.Identity)]publicint?Id{get;set;}[MaxLength(10,ErrorMessage="Unit number too long")][Display(Name="Unit #")]publicstringUnitNumber{get;set;}[MaxLength(45,ErrorMessage="BuildingName name too long")]publicstringBuildingName{get;set;}[MaxLength(45,ErrorMessage="Street too long")]publicstringStreet{get;set;}}}

So when I navigate to that page, the controller gets triggered, and correctly returns the Edit view. I have also confirmed the "id" parameter is indeed populated with the id of the object I wish to edit. However, the Edit view loads in the browser, all the input textboxes are empty. I would expect them to be pre-populated with the values for the object in question. What am I missing?

Thanks...

System.Diagnostics.DiagnosticSource Exception

$
0
0

Hi All,

I got below exception in ASP.Net core.

Layer:

Business => Data, Common

Web=> Business

System.IO.FileLoadException occurred
  HResult=0x80131040
  Message=Could not load file or assembly 'System.Diagnostics.DiagnosticSource, Version=4.0.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)
  Source=Microsoft.ApplicationInsights.AspNetCore
  StackTrace:
   at Microsoft.Extensions.DependencyInjection.ApplicationInsightsExtensions.AddApplicationInsightsTelemetry(IServiceCollection services)
   at Microsoft.AspNetCore.Hosting.ApplicationInsightsWebHostBuilderExtensions.<>c.<UseApplicationInsights>b__0_0(IServiceCollection collection)
   at Microsoft.AspNetCore.Hosting.WebHostBuilder.BuildCommonServices()
   at Microsoft.AspNetCore.Hosting.WebHostBuilder.Build()
   at ParticleTrack.Web.Program.Main(String[] args) in F:\VSTS\Track\PTrack.Web\Program.cs:line 14

==========
Could not load file or assembly 'System.Diagnostics.DiagnosticSource, Version=4.0.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)

Thanks,

How can I create my own Scaffolding on Visual Studio 2017?

$
0
0

Hello everyone, I'm starting using ASP.NET Core and I come from Node.js world. Laughing

I'm following this beginners guide using Visual Studio Community 2017, it's a fantastic tool, but when I started using the Scaffolding I got some questions.

Why the MVC Scaffolding Controller don't use HTTP verbs (PUT / DELETE / etc.)?
But the API Scaffolding does use the HTTP verbs, here an example.

At present all browsers support those HTTP verbs, don't they? or what is the reason why they don't use it?

How can I create my own Scaffolding (Controllers and Views) on Visual Studio 2017?

Howto? Visual Studio Windows + .net core web app + Ubuntu 16.04-arm server.

$
0
0

I am wondering whether it is possible to deploy a .net core web app developed in Visual Studio, to Raspberry Pi, and if so , how ?

I am using VS2017 Community edition on Windows 10. I have created a new .Net Core project using the Web App option. If I build and run, I correctly get the default web page opening up on the local browser. So far, fine. I then publish to a folder and copy all my files using WinSCP to a Raspberry Pi running Ubuntu Server 16.04-arm.

Yes, Microsoft are doing a great job in opening up the .net sources and building their capability across platforms, sadly not arm as yet but Im sure now Softbank own Arm and companies like Samsung are joining the party, we will see a great future for .net hopefully taking over Sun/Java. Anyway, meantime the ubunutu Pi obviously is an arm so not directly supported yet so it has a dotnet core installation from github  https://github.com/dotnet/core/blob/master/samples/RaspberryPiInstructions.md  and followed their instructions to install 2.0.0-beta-001620-00 onto the Pi and confirmed all okay by running dotnet on the Pi, and indeed all was well.

However, what is the next steps...?

I cant seem to publish to ftp . Is there a bug? the connection is verified okay and the publish folder is correctly created (yes I have correct vsftpd config) on the Pi, but no files are copied over?

How do I publish my .net core web app from VS2017 to the Pi please?

Models repeated for both web app and web API?

$
0
0

I am busy creating an ASP .Net MVC 1.1 Web App. This will server as the front end. I am also creating an ASP .Net MVC 1.1 Web API. This will server as the back end to the web app, as well as to a phone app that a colleague is developing.

My question is, the web app and web API share many of the same models. For example, in a car dealership, the web app might have a form to add a new car. The user would fill in all the fields in the form and hit submit. The web app would then perform an HTTP POST to the Web API, passing this car model to the Web API controller, which would receive the car model as a parameter. So, in this case, both web app and web API would have a copy of the car model.

What is the correct way to handle this? Do I need to have a car model in the "Models" folder of both my web app project and my web API project in the "Car Dealership" solution? And if I have to add a field (such as mileage) I would add it to both models (as well as to the database and to the HTML form)? Is there no way to share models? I just want to make sure I'm doing things correctly - I'm very new to ASP .Net (and web development in general)

Thanks


Debug not working in VS2015

$
0
0

App being debugged in Visual Studio 2015 is not stopping at breakpoints, even though the code where those breakpoints are defined is definitely being executed.  Debug was working 2 days ago (Wed 10 Apr 2017), but on Thursday it wasn't and I haven't figured out why as of today, Friday.  I am running VS2015 in Administrator mode on my desktop on Windows 7 SP1.  VS2015 is at Update 3.  I have debug="true" in my web.config file, and ASP.NET and Native code debuggers are checked in my project properties.

What else could I be missing? (And, why is it so bloody difficult to accomplish anything in VS - rhetorical question, no need to answer).

Any help would be greatly appreciated.

If it's of any help ,here's the code behind the page:

Imports System.IO
Imports System.Data
Imports System.Data.SqlClient
Imports System.Xml
Imports System.Net
Public Class _ExportLabelXML
    Inherits System.Web.UI.Page

    Dim strManufdate As Date
    Dim strUseByDate As Date
    Dim intShelfLifeDays As Int16
    Dim strColName As String
    Dim strColType As String
    Dim strColValue As String
    Dim strConnString As String = "Server=vdfy-tro-db01; Database=livedb; Integrated Security=false; " &"Connect Timeout=300; User=rolivedb; Password=rolivedb"
    Dim cnnTroposConnection As New SqlConnection(strConnString)
    Dim cmdLabelQry As String ="SELECT " &" [Partno_txt] " &",[Partno_Short] As [SKU Number] " &",[Description_txt] As [Item Description] " &",[Prodgroup] As [Product Group Code] " &",' ' As [Allergen Info] " &",[Text_Safety] As [Handling Instructions] " &",[ITF14Number] As [UPC Number] " &",Case When PATINDEX('%-%',[Partno_txt]) <> 0 Then RIGHT(rtrim([Partno_txt]),3) Else ' ' End As [Plant Number] " &",[Text_Contains] As [Ingredients] " &",[USDAGraphic] As [USDA Graphic] " &",[TrademarkGraphic] As [Trademark Graphic] " &",[QtyPerCase] As [Quantity Per Case] " &",[CaseWeightLbs] As [Case Weight lb] " &",[UnitWeightLbs] As [Unit Weight lb] " &",[CaseWeightKgs] As [Case Weight gm] " &",[UnitWeightgms] As [Unit Weight gm] " &"FROM [livedb].[dbo].[VDFY_vw_GetText] " &"WHERE Partno_txt = @SKU_Number "
    Dim cmdGetShelfLife As String ="SELECT SHELFLIFE FROM MBC010 WHERE PARTNO_INV = @SKU_Number and ACCOUNT15_INV = '000010000100001' and " &"WAREHOUSE = ' ' and LOCSTOR_INV = ' ' and LOCBIN_INV = ' '"
    Dim sqlCmdGetLabel As New SqlCommand(cmdLabelQry, cnnTroposConnection)
    Dim sqlCmdGetShelfLife As New SqlCommand(cmdGetShelfLife, cnnTroposConnection)
    Dim strSKUNumber As String
    Dim strFileName As String
    Dim strFilePath As String = "C:\TEMP\"
    Dim strURIPath As String = "file://C/TEMP/"
    Dim strDwnLodPath As String = "C:\Users\peterst\Documents\Access Projects"
    Dim xmlLblWriter As XmlWriter
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        lblMessage.Text = ""
    End Sub

    Protected Sub btnGenLabelFile_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnGenLabelFile.Click
        Dim xmlLabelWriterSettings As New XmlWriterSettings()

        If Page.IsValid Then
            ' Set sqlCmdGetLabel parameters
            sqlCmdGetLabel.Parameters.Add("@SKU_Number", SqlDbType.Char)
            sqlCmdGetLabel.Parameters("@SKU_Number").Value = txItemNumber.Text
            ' Set sqlCmdGetShelfLife parameters
            sqlCmdGetShelfLife.Parameters.Add("@SKU_Number", SqlDbType.Char)
            sqlCmdGetShelfLife.Parameters("@SKU_Number").Value = txItemNumber.Text
            ' Set xmlLabelWriterSettings
            xmlLabelWriterSettings.CheckCharacters = True
            xmlLabelWriterSettings.CloseOutput = True
            xmlLabelWriterSettings.Indent = True
            xmlLabelWriterSettings.IndentChars = vbTab
            xmlLabelWriterSettings.NewLineChars = vbCrLf
            ' Set output label file name
            strFileName = "Label_" & Left(txItemNumber.Text, InStr(txItemNumber.Text, "-") - 1) & ".xml"
            ' Set SKU number for file name buildString
            strSKUNumber = Left(txItemNumber.Text, InStr(txItemNumber.Text, "-") - 1)
            strManufdate = CDate(txManufDate.Text)
            strUseByDate = CDate(txManufDate.Text)

            cnnTroposConnection.Open()
            Dim sqlReader As SqlDataReader = sqlCmdGetShelfLife.ExecuteReader()
            If sqlReader.HasRows Then
                sqlReader.Read()
                intShelfLifeDays = sqlReader.GetDecimal(sqlReader.GetOrdinal("SHELFLIFE"))
            Else
                intShelfLifeDays = 0
            End If
            strUseByDate = DateAdd(DateInterval.Day, intShelfLifeDays, strUseByDate)
            'strUseByDate = DateAdd(DateInterval.Day, intShelfLifeDays, strUseByDate)
            sqlReader.Close()
            sqlReader = sqlCmdGetLabel.ExecuteReader()
            If sqlReader.HasRows Then
                ' Create XML output file
                xmlLblWriter = XmlWriter.Create(strFilePath & strFileName, xmlLabelWriterSettings)
                ' Start writing XML
                xmlLblWriter.WriteStartElement("Label")
                xmlLblWriter.WriteStartElement("Printer_Info")
                xmlLblWriter.WriteStartElement("Printer")
                xmlLblWriter.WriteValue(txPrinter.Text)
                xmlLblWriter.WriteEndElement() ' End Printer element
                xmlLblWriter.WriteStartElement("Copies")
                xmlLblWriter.WriteValue(txLabelQty.Text)
                xmlLblWriter.WriteEndElement() ' End Copied element
                xmlLblWriter.WriteEndElement() ' End Printer Info element

                xmlLblWriter.WriteStartElement("Label_Info")
                While sqlReader.Read()
                    For iColumn As Integer = 0 To sqlReader.FieldCount - 1
                        strColName = sqlReader.GetName(iColumn)
                        strColType = sqlReader.GetDataTypeName(iColumn)
                        If Not IsDBNull(sqlReader.GetValue(iColumn)) Then
                            strColValue = CStr(sqlReader.GetValue(iColumn))
                        Else
                            strColValue = " "
                        End If
                        If strColType = "varchar" Then
                            ReplaceSpecialXMLChar(strColValue)
                        End If
                        xmlLblWriter.WriteStartElement(Replace(strColName, " ", ""))
                        xmlLblWriter.WriteValue(strColValue)
                        xmlLblWriter.WriteEndElement()
                    Next
                End While
                xmlLblWriter.WriteStartElement("Manufactured_Date")
                xmlLblWriter.WriteValue(Format(strManufdate, "yyyy-MM-dd"))
                xmlLblWriter.WriteEndElement()
                xmlLblWriter.WriteStartElement("Use_By_Date")
                xmlLblWriter.WriteValue(Format(strUseByDate, "yyyy-MM-dd"))
                xmlLblWriter.WriteEndElement()
                xmlLblWriter.WriteEndElement()
                xmlLblWriter.WriteEndElement()
                xmlLblWriter.Close()
                sqlReader.Close()

                DownloadLabelFile()

                lblMessage.ForeColor = Drawing.Color.Green
                lblMessage.Font.Bold = True
                lblMessage.Text = "Item " & txItemNumber.Text & " label created."
                ClearInputBoxes()
            Else
                lblMessage.ForeColor = Drawing.Color.Red
                lblMessage.Font.Bold = True
                lblMessage.Text = "Item " & txItemNumber.Text & " does not exist!"
                ClearInputBoxes()
            End If
        End If
    End Sub

    Protected Sub ManufDateFormatValidator_ServerValidate(source As Object, args As ServerValidateEventArgs) Handles ManufDateFormatValidator.ServerValidate
        Try
            DateTime.ParseExact(args.Value, "d", Nothing)
            args.IsValid = True
        Catch
            args.IsValid = False
        End Try
    End Sub
    Protected Function ReplaceSpecialXMLChar(ByRef XMLValue As String) As String
        Replace(XMLValue, "&amp;", "&",,)
        Replace(XMLValue, "&lt;", "<",,)
        Replace(XMLValue, "&gt;", ">",,)
        Replace(XMLValue, "&apos;", "'",,)
        Replace(XMLValue, "&quot;", """",,)
        ReplaceSpecialXMLChar = XMLValue
        Exit Function
    End Function

    Protected Sub ClearInputBoxes()
        txItemNumber.Text = ""
        txManufDate.Text = ""
        txLabelQty.Text = ""
        txPrinter.Text = ""
    End Sub

    Public Sub DownloadLabelFile()
        Dim objWebClient As New WebClient()
        Dim objInnerEx As New Exception
        Dim mpeWarningWindow As New AjaxControlToolkit.ModalPopupExtender
        'Try
        objWebClient.DownloadFile(strURIPath, strDwnLodPath)
            lblWarnMessage.Text = "Label for " & strSKUNumber & " created."
        'Catch ex As Exception
        'objInnerEx = ex.InnerException
        'lblWarnMessage.Text = "Error: " & objInnerEx.Message & vbCrLf & objInnerEx.HResult.ToString

        'mpe1.Show()
        'mpeWarningWindow.
        'MsgBox(CStr(ex.HResult) & " " & ex.Message & " " & ex.HelpLink)
        'MsgBox(CStr(objInnerEx.HResult) & " " & objInnerEx.Message & " " & objInnerEx.HelpLink)
        'End Try
    End Sub

End Class

How to Publish an ASP.NET Core website in linux host

$
0
0

hi plz help me
Getting help  me about publish an asp.net core website in linux centos host or others
1.publishing in linux  is by which contorol panel?   
2.by which Service Providers?
3.sql server has to install in linux for databas and its Necessary?
4.all the Features and Facilities of asp.net core in linux is Supported?
5.and is asp.net core for linux is trial or full version?
6.is microsoft upgrade asp.net core for linux and linux Prerequisites for publish like .NET Core SDK and apps is support and upgrade  by microsoft?? 

How to use Crystal report in AspNetCore.Mvc.

$
0
0

Hi Team, 

I have converted existing Erp Application from Ap.net MVC to AspNetCore.Mvc. I want to integrate crystal report to new application. I have added the reference of 

  • CrystalDecisions.CrystalReports.Engine.dll
  • CrystalDecisions.ReportSource.dll
  • CrystalDecisions.Web.dll

But when I try to to use Load, SetDataSource functions of CrystalDecisions.CrystalReports.Engine ReportDocument , It shows compilation error as 

The type 'IDataReader' is defined in an assembly that is not referenced. You must add a reference to assembly 'System.Data, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'.

This is my code to load  Crystal report

ReportDocument rd = new ReportDocument();
rd.Load(Path.Combine(Server.MapPath("~/Reports"), "rpt_EverestList.rpt"));
rd.SetDataSource(bUnits);

Is there any better option to use crystal report in AspNetCore.Mvc ?

Thanks & Regards

Sunij K

Multiple Submit Buttons

$
0
0

Not sure where I am going wrong.  I have a wizard type form.  On the form I have a next and back button.  So far I have the next button working which is fine as this is intentional at this stage.  On this particular form in the sequence I want to add a third button for Add Another Procedure.

View Code:

@{
    ViewData["Title"] = "Add Procedure";
}<h2>Add Procedure To Quote</h2><form asp-action=" " method="post"><div class="form-horizontal"><hr /><div asp-validation-summary="ModelOnly" class="text-danger"></div><div class="form-group"><label class="col-md-2 control-label">Quote</label><div class="col-md-10"><select asp-for="QuoteID" class="form-control" asp-items="ViewBag.QuoteID" id="quoteID"><option>---Select Quote ---</option></select></div></div>
......<div class="form-group"><div class="col-md-offset-2 col-md-10"><input type="submit" value="Add Another Procedure" formaction="AddAnotherProcedure"  id="buttonrefresh" /></div></div><div class="form-group"><div class="col-md-offset-2 col-md-10"><input type="submit" value="<Back" class="btn btn-default" />   <input type="submit" value="Next>" formaction="QuoteSalesProcedure"  /></div></div></div></form>

Then in the controller I have:

 // POST: QuoteProcedures/AddAnotherProcedure
        // 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 async Task<IActionResult> AddAnotherProcedure([Bind("EstimateMinutes,FrequencyID,ProcedureID,Quantity,QuoteID")] QuoteProcedure quoteProcedure)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    _context.Add(quoteProcedure);
                    await _context.SaveChangesAsync();



                    return RedirectToAction("QuoteSalesAnotherProcedure",  new { id = quoteProcedure.QuoteID });
                }
            }
            catch (DbUpdateException /* ex */)
            {
                //Log the error (uncomment ex variable name and write a log.
                ModelState.AddModelError("", "Unable to save changes. " +"Try again, and if the problem persists " +"see your system administrator.");
            }



            return RedirectToAction("QuoteSalesAnotherProcedure", new { id = quoteProcedure.QuoteID });
        }

        // GET: QuoteProcedures/Create
        public IActionResult QuoteSalesAnotherProcedure(int id)
        {
            ViewData["FrequencyID"] = new SelectList(_context.Frequency.OrderBy(i => i.iFrequency), "FrequencyID", "iFrequency");
            ViewData["ProcedureID"] = new SelectList(_context.Procedures.OrderBy(p => p.ProcedureName), "ProcedureID", "ProcedureName");
            ViewData["QuoteID"] = new SelectList(_context.Quote.Include(q => q.QuoteRequest).OrderBy(q => q.QuoteRequest.QDescription),"QuoteID", "QuoteRequest.QDescription", id);
            ViewData["IDD"] = id;

            return View();
        }

However this doesn't seem to work.  My intent is to save the current procedure and reload the form.

If I get the form to reload, with mucking about, it doesn't save the record to the table and the next button fails to respond.  If I get the record to save then it doesn't reload for the next procedure so I assume it is going to the original create method.

Clearly I am not following something?  What is the issue?  How have I misunderstood?

Session managment , .net core webapi

$
0
0

I am working with enterprice application with .net core web.api + angular2.  Around 1,00,000 users will use this app one it is on production.

Some api is expose to another client ( Window base application ). 

Currently i am using Jwt token for authentication.  

How can i store session data. Application will deploy on azure with PAAS multiple app service. 

Contoso - Sort a Table on Details Page

$
0
0

Hi,

While following the learning package at https://docs.microsoft.com/en-us/aspnet/core/data/ef-mvc/crud, I want to know what changes to be made in the following code so as to have the Course Details table be available in the sortable manner (like on the Index page at https://docs.microsoft.com/en-us/aspnet/core/data/ef-mvc/sort-filter-page). I can call the Details method with an argument delivering the sort manner required but how to have the var student use the OrderBy & OrderByDescending since the same are complained by the VS2013 to be not IQueryable in nature

public async Task<IActionResult> Details(int? id)
{
    if (id == null)
    {
        return NotFound();
    }

    var student = await _context.Students
        .Include(s => s.Enrollments)
            .ThenInclude(e => e.Course)
        .AsNoTracking()
        .SingleOrDefaultAsync(m => m.ID == id);

    if (student == null)
    {
        return NotFound();
    }

    return View(student);
}

While code for the Index page, like the following, works great for the var students:

public async Task<IActionResult> Index(string sortOrder)
{
    ViewData["NameSortParm"] = String.IsNullOrEmpty(sortOrder) ? "name_desc" : "";
    ViewData["DateSortParm"] = sortOrder == "Date" ? "date_desc" : "Date";
    var students = from s in _context.Students
                   select s;
    switch (sortOrder)
    {
        case "name_desc":
            students = students.OrderByDescending(s => s.LastName);
            break;
        case "Date":
            students = students.OrderBy(s => s.EnrollmentDate);
            break;
        case "date_desc":
            students = students.OrderByDescending(s => s.EnrollmentDate);
            break;
        default:
            students = students.OrderBy(s => s.LastName);
            break;
    }
    return View(await students.AsNoTracking().ToListAsync());
}

Thanks in advance.

RedirectToAction or Redirect?

$
0
0

I'm wondering what is the most effective way of returning from an editpost method to the Edit view?

So after updating a post I can either do this

return RedirectToAction("Edit", new { ID = id });

or this:

string url = $"/Post/Edit/{id}";

return Redirect(url);

The edit action method(that both these return statements sends an id to) is just the standard fetch whatever post that belongs to id, populate it in a viewmodel and return it to view.

I'm wondering if using Redirect() is faster or has some benefits over the first one? Maybe the only difference is that in the redirectto action i also create a new variable, and that they work exactly the same in my case?


Referencing multiple models in ViewModel from View

$
0
0

I have an ASP .Net Core 1.1 MVC web app. The app will be used by real estate agents to manage properties. The web app gets all it's data from a Web API. The web app has a page where a user can edit an existing property. The page has some simple textbox type inputs, and a dropdown list to select the type of property (house, flat, simplex, duplex, office, shop, etc). So, it has:
 
These two models:

   

 namespace InspectionsData.Models    {        [Table("property")]        public class Property        {            [Key]            [DatabaseGenerated(DatabaseGeneratedOption.Identity)]            public int? Id { get; set; }            public string Street1 { get; set; }            public string City { get; set; }            public string Region { get; set; }            public string Country { get; set; }            public PropertyType PropertyType { get; set; }
and    namespace InspectionsData.Models    {        public partial class PropertyType        {            [Key]            [DatabaseGenerated(DatabaseGeneratedOption.Identity)]            public int Id { get; set; }            public string PropertyTypeName { get; set; }        }    }

A ModelView:

    namespace InspectionsTestClient.ViewModels    {        public class PropertyIndexViewModel        {            public Property Property { get; set; }            public List<PropertyType> PropertyTypes { get; set; }        }    }

a controller:

    // GET: Property/Edit/5            public async Task<ActionResult> Edit(int id)            {                if (!ModelState.IsValid)                {                    return BadRequest(ModelState);                }                   string url = propertiesUrl + "/" + id.ToString();                HttpResponseMessage responseMessage = await client.GetAsync(url);                if (responseMessage.IsSuccessStatusCode)                {                    var responseData = responseMessage.Content.ReadAsStringAsync().Result;                    var @property = Newtonsoft.Json.JsonConvert.DeserializeObject<Property>(responseData);                    if (@property == null)                    {                        return NotFound();                    }                       List<PropertyType> propertyTypes = null;                    url = apiUrl + "PropertyTypes";                    responseMessage = await client.GetAsync(url);                    if (responseMessage.IsSuccessStatusCode)                    {                        responseData = responseMessage.Content.ReadAsStringAsync().Result;                        propertyTypes = Newtonsoft.Json.JsonConvert.DeserializeObject<List<PropertyType>>(responseData);                    }                       PropertyIndexViewModel vm = new PropertyIndexViewModel()                    {                        Property = @property,                        PropertyTypes = propertyTypes                    };                       return View(vm);                }                   return View("Error");            }

And a view:

    @model InspectionsTestClient.ViewModels.PropertyIndexViewModel       @{        ViewData["Title"] = "Edit";    }       @{        Layout = "_Layout";    }       <h2>Edit</h2>       @Html.ValidationSummary();       <form asp-action="Edit">        <div class="form-horizontal">            <h4>Property</h4>            <hr />            <div class="form-group">                <label asp-for="Property.Street" class="col-md-2 control-label"></label>                <div class="col-md-10">                    <input asp-for="Property.Street" class="form-control" />                    <span asp-validation-for="Street" class="text-danger"></span>                </div>            </div>            <div class="form-group">                <label asp-for="Property.City" class="col-md-2 control-label"></label>                <div class="col-md-10">                    <input asp-for="Property.City" class="form-control" />                    <span asp-validation-for="City" class="text-danger"></span>                </div>            </div>               <div class="form-group">                <label asp-for="Property.Region" class="col-md-2 control-label"></label>                <div class="col-md-10">                    <input asp-for="Property.Region" class="form-control" />                    <span asp-validation-for="Region" class="text-danger"></span>                </div>            </div>            <div class="form-group">                <label asp-for="Property.Country" class="col-md-2 control-label"></label>                <div class="col-md-10">                    <input asp-for="Property.Country" class="form-control" />                    <span asp-validation-for="Country" class="text-danger"></span>                </div>            </div>            <div class="form-group">                <label asp-for="Property.PropertyType" class="col-md-2 control-label"></label>                <div class="col-md-10">                    <input asp-for="Property.PropertyType" class="form-control" />                    <span asp-validation-for="PropertyType" class="text-danger"></span>                </div>            </div>            <div class="form-group">                <div class="col-md-offset-2 col-md-10">                    <input type="submit" value="Save" class="btn btn-default" />                </div>            </div>        </div>    </form>       <div>        <a asp-action="Index">Back to List</a>    </div>       @section Scripts {        @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}    }

Now, in my view, the PropertyType is still a text type input - not  a dropdown. But that's ok, I will sort that out shortly (I'm taking one step at a time - I'm very new to web development).

Now, I don't know if I'm following the correct approach, but I have created a ViewModel so that I can feed the View both the Property object, as well as the List of PropertyTypes for the dropdown list, since the view needs both of these to work properly. I don't know if perhaps I should rather have a DTO that the Web Api returns that already has the property and list of property types in it (instead of making two separate calls to the web API to fetch each)? Or if perhaps the web app should request all the property types from the web API at startup and keep them cached as these won't be changing?

But be that as it may - for now, I'd like to try and figure out what I am doing wrong with my current (probably flawed) approach.

When I run the app, the controller works 100% and fetches all the data, but when the view fires up, I get this error:

    

Type expected    +            #pragma warning restore 1998 Type expected    +            #pragma warning restore 1998 Type expected    +            #pragma warning restore 1998 Type expected    +            #pragma warning restore 1998 Type expected    +            #pragma warning restore 1998 Type expected    +            #pragma warning restore 1998 'PropertyIndexViewModel' does not contain a definition for 'Street' and no extension method 'Street' accepting a first argument of type 'PropertyIndexViewModel' could be found (are you missing a using directive or an assembly reference?)    +            #pragma warning restore 1998 'PropertyIndexViewModel' does not contain a definition for 'City' and no extension method 'City' accepting a first argument of type 'PropertyIndexViewModel' could be found (are you missing a using directive or an assembly reference?)    +            #pragma warning restore 1998 'PropertyIndexViewModel' does not contain a definition for 'Region' and no extension method 'Region' accepting a first argument of type 'PropertyIndexViewModel' could be found (are you missing a using directive or an assembly reference?)    +            #pragma warning restore 1998 'PropertyIndexViewModel' does not contain a definition for 'Country' and no extension method 'Country' accepting a first argument of type 'PropertyIndexViewModel' could be found (are you missing a using directive or an assembly reference?)    +            #pragma warning restore 1998 'PropertyIndexViewModel' does not contain a definition for 'PropertyType' and no extension method 'PropertyType' accepting a first argument of type 'PropertyIndexViewModel' could be found (are you missing a using directive or an assembly reference?)

In my view, I am suspecting that I cannot do this:

    <input type="hidden" asp-for="Property.Id" />

But I'm not sure how to reference the specific object in the ModelView... Any ideas?

Can you point directly to the site with IP_public:port ?

Getting selected option of SELECT from View back to Controller

$
0
0

I have an ASP .Net Core 1.1 MVC web app. The app talks to a web API backend to read/write data to the data store.

In the web app, I have an Edit page, where you can edit a record of a particular object. One of the fields in the record is a dropdownlist (i.e. an HTML <SELECT> tag). My problem is I don't know how to get the selected option from the dropdownlist (in the View) back to the controller.

To give you brief background, this web app will be used by real estate agents to manage their properties. To simply things, for now the property has a basic structure - an ID, and address and a "Property Type" (house, flat, office, etc)

So I have these two models:

using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

namespace InspectionsData.Models
{
    public partial class PropertyType
    {
        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public int Id { get; set; }
        public string PropertyTypeName { get; set; } // e.g. house, flat, office, etc.
    }
}

and

using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

namespace InspectionsData.Models
{
    [Table("property")]
    public class Property
    {

        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public int? Id { get; set; }
        public string Street { get; set; }
        public string City { get; set; }
        public string Region { get; set; }
        public string Country { get; set; }
        public int? PropertyTypeId { get; set; }
        [ForeignKey("PropertyTypeId")]
        public PropertyType PropertyType { get; set; }
    }
}

I then created a ViewModel so that I can feed both of the above models to the view:

using InspectionsData.Models;
using Microsoft.AspNetCore.Mvc.Rendering;

namespace InspectionsTestClient.ViewModels
{
    public class PropertyIndexViewModel
    {
        public Property Property { get; set; }
        public SelectList PropertyTypes { get; set; }
    }
}

Then I have a controller which populates the view:

// GET: Property/Edit/5
        public async Task<ActionResult> Edit(int id)
        {
            string apiUrl = "http://localhost:50082/api/";

if (!ModelState.IsValid) { return BadRequest(ModelState); } //Read property from Web API
string url = apiUrl + "Properties/" + id.ToString(); HttpResponseMessage responseMessage = await client.GetAsync(url); if (responseMessage.IsSuccessStatusCode) { var responseData = responseMessage.Content.ReadAsStringAsync().Result; var prop = Newtonsoft.Json.JsonConvert.DeserializeObject<Property>(responseData); if (prop == null) { return NotFound(); } List<PropertyType> propertyTypes = null; url = apiUrl + "PropertyTypes"; responseMessage = await client.GetAsync(url); if (responseMessage.IsSuccessStatusCode) { responseData = responseMessage.Content.ReadAsStringAsync().Result; propertyTypes = Newtonsoft.Json.JsonConvert.DeserializeObject<List<PropertyType>>(responseData); } PropertyIndexViewModel vm = new PropertyIndexViewModel() { Property = prop, PropertyTypes = new SelectList(propertyTypes, "Id", "PropertyTypeName") }; return View(vm); } return View("Error"); }

I know it's inneficient in making two calls to the API - one to get the property and one to ge the list of Property Types - I will improve this later, but for now that's how it is...

and the view:

@model InspectionsTestClient.ViewModels.PropertyIndexViewModel

@{
    ViewData["Title"] = "Edit";
}

@{
    Layout = "_Layout";
}<h2>Edit</h2>

@Html.ValidationSummary();

<form asp-action="Edit"><div class="form-horizontal"><h4>Property</h4><hr /><div asp-validation-summary="ModelOnly" class="text-danger"></div><input type="hidden" asp-for="Property.Id" /><div class="form-group"><label asp-for="Property.Street" class="col-md-2 control-label"></label><div class="col-md-10"><input asp-for="Property.Street" class="form-control" /><span asp-validation-for="Property.Street" class="text-danger"></span></div></div><div class="form-group"><label asp-for="Property.City" class="col-md-2 control-label"></label><div class="col-md-10"><input asp-for="Property.City" class="form-control" /><span asp-validation-for="Property.City" class="text-danger"></span></div></div><div class="form-group"><label asp-for="Property.Region" class="col-md-2 control-label"></label><div class="col-md-10"><input asp-for="Property.Region" class="form-control" /><span asp-validation-for="Property.Region" class="text-danger"></span></div></div><div class="form-group"><label asp-for="Property.Country" class="col-md-2 control-label"></label><div class="col-md-10"><input asp-for="Property.Country" class="form-control" /><span asp-validation-for="Property.Country" class="text-danger"></span></div></div><div class="form-group"><label asp-for="Property.PropertyType" class="col-md-2 control-label"></label><div class="col-md-10"><select asp-for="Property.PropertyType" asp-items="@Model.PropertyTypes"></select></div></div><div class="form-group"><div class="col-md-offset-2 col-md-10"><input type="submit" value="Save" class="btn btn-default" /></div></div></div></form><div><a asp-action="Index">Back to List</a></div>

@section Scripts {
    @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}

When the user clicks the SAVE button on the form, it posts back to another controller action:

// POST: Property/Edit/5
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<ActionResult> Edit(int id, Property prop)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    string apiUrl = "http://localhost:50082/api/";                    
string url = apiUrl + "properties/" + id.ToString(); string jsonInString = JsonConvert.SerializeObject(prop); HttpContent content = new StringContent(jsonInString, Encoding.UTF8, "application/json"); HttpResponseMessage responseMessage = await client.PutAsync(url, content); if (responseMessage.IsSuccessStatusCode) { return RedirectToAction("Index"); } } return View(); } catch { return View(); } }

So this controller action posts the updated property to the web API. The problem is that, everything works 100% until it gets to this final controller action - if I inspect the "prop" parameter, it contains all the modifications made, but it does not contain the selected PopertyType - how can I return the selected PropertyType from the view back to the controller?

Thanks...

There was an error running the selected code generator

$
0
0

Trying to do a controller scaffolding in a ASP.NET Core solution and I get the following error:

---------------------------
Microsoft Visual Studio
---------------------------
Error

There was an error running the selected code generator:

'Unable to write data to the transport connection: An established connection was aborted by the software in your host machine.
Unhandled Exception: System.AggregateException: One or more errors occurred.
(Unable to write data to the transport connection:
An established connection was aborted by the software in your host machine.)
---> System.IO.IOException: Unable to write data to the transport connection:
An established connection was aborted by the software in your host machine. --->
System.Net.Sockets.SocketException: An established connection was aborted by the software in your host machine
at System.Net.Sockets.Socket.Send(Byte[] buffer, Int32 offset, Int32 size, SocketFlags socketFlags)
at System.Net.Sockets.NetworkStream.Write(Byte[] buffer, Int32 offset, Int32 size)
--- End of inner exception stack trace ---
at Microsoft.VisualStudio.Web.CodeGeneration.Design.ScaffoldingClient.Send(Message message)
at Microsoft.VisualStudio.Web.CodeGeneration.Design.Program.<GetProjectInformationFromServer>d__6.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.VisualStudio.Web.CodeGeneration.Design.Program.<>c__DisplayClass5_0.<<Execute>b__0>d.MoveNext()
--- End of inner exception stack trace ---
at System.Threading.Tasks.Task.ThrowIfExceptional(Boolean includeTaskCanceledExceptions)
at System.Threading.Tasks.Task`1.GetResultCore(Boolean waitCompletionNotification)
at Microsoft.Extensions.CommandLineUtils.CommandLineApplication.Execute(String[] args)
at Microsoft.VisualStudio.Web.CodeGeneration.Design.Program.Main(String[] args)'
---------------------------
OK
---------------------------

I have the latest build of visual studio 2017 RC. 

In projects csproj file I have the latest refrences:

<ItemGroup>
<DotNetCliToolReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Tools" Version="1.0.0-msbuild3-final" />
</ItemGroup>

 <PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="1.1.1" />

===

I found in the event viewer that every time I try to do a scafolding, dotnet.exe is crashing in the background.

Fault bucket 129390288245, type 5
Event Name: CLR20r3
Response: Not available
Cab Id: 0

Problem signature:
P1: C:\Program Files\dotnet\dotnet.exe
P2: 1.1.0.1179
P3: 5820b092
P4: System.Net.Sockets
P5: 4.6.24705.1
P6: 581d6231
P7: 187
P8: 17
P9: System.AggregateException
P10:

Attached files:
\\?\C:\ProgramData\Microsoft\Windows\WER\Temp\WER7A90.tmp.mdmp
\\?\C:\ProgramData\Microsoft\Windows\WER\Temp\WER7B8B.tmp.WERInternalMetadata.xml
\\?\C:\ProgramData\Microsoft\Windows\WER\Temp\WER7B8C.tmp.csv
\\?\C:\ProgramData\Microsoft\Windows\WER\Temp\WER7BAD.tmp.txt

These files may be available here:
C:\ProgramData\Microsoft\Windows\WER\ReportArchive\AppCrash_C__Program Files_f41bf27ea39ac572c183c70b1a647b1d5fdfbab_66e69dae_3d448260

Analysis symbol:
Rechecking for solution: 0
Report Id: 19b7e4e4-fb57-487d-81b6-528f04a11eb7
Report Status: 268435456
Hashed bucket: 57d54f0839232cc5a9588d9f015bb19f

Using a Cookie in a Model

$
0
0

I would like to make a function in a model to access a cookie.  The reason I want to do this, is so I can easily call this function from throughout the site to get this piece of information (such as a UserID).  However, I've found that I can only access cookies via the Controller.  Do I need to make this function in a controller and reference the controller all the time, or am I doing something completely wrong.  I have a feeling the second answer is probably right :)

Thanks for any help!

Viewing all 9386 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>