dotnet .net

Upload with form

model

public class ProductEditModel
    {
        public int ID { get; set; }
        public string Name { get; set; }
        public decimal Rate { get; set; }
        public int Rating { get; set; }
    }

controller
[HttpGet]
        public IActionResult Create()
        {
            return View();
        }


        [HttpPost]
        public IActionResult Create(ProductEditModel model)
        {
            string message = "";

            if (ModelState.IsValid)
            {
                message = "product " + model.Name + " Rate " + model.Rate.ToString() + " With Rating " + model.Rating.ToString() + " created successfully";
                ProductEditModel p = new ProductEditModel();
                p.Name = model.Name;
                p.Rate = model.Rate;
                p.Rating = model.Rating;
                ViewData["product"] = p;
                ViewData["isSuccess"] = true;

            }
            else
            {
                ViewData["isError"] = true;
                message = "Failed to create the product. Please try again";
            }
            ViewData["Message"] = message;
            return View();
        }

razor
@{
    ViewData["Title"] = "Bla Create";
    var product = ViewData["Product"] as ProductEditModel;
    var isSuccess = ViewData["isSuccess"] as Boolean?;
    var isError = ViewData["isError"] as Boolean?;
}

<h2>Create</h2>
@if (@isSuccess == true)
{

    <div class="alert alert-success" role="alert">
        @ViewData["Message"]
    </div>
}
@if (@isError == true)
{

    <div class="alert alert-danger" role="alert">
        @ViewData["Message"]
    </div>
}

@if (@product != null)
{
    <p>
        <a asp-area="" asp-controller="Bla" asp-action="Create">Create</a>
        <a asp-area="" asp-controller="Bla" asp-action="Index">Bla</a>
    </p>

}
else
{
    <form action="/bla/create" method="post">
        <label for="Name">Name</label>
        <input type="text" name="Name" />

        <label for="Rate">Rate</label>
        <input type="text" name="Rate" />
        <label for="Rating">Rating</label>
        <input type="text" name="Rating" />
        <input type="submit" name="submit" />
    </form>
}

html linking

<a asp-area="" asp-controller="Bla" asp-action="Index">Bla</a>

Routing mvc dotnet core

In startup.cs

app.UseMvc(routes =>
{
    //New Route
    routes.MapRoute(
       name: "about-route",
       template: "about",
       defaults: new { controller = "Home", action = "About" }
    );

routes.MapRoute(
    name: "default",
    template: "{controller=Home}/{action=Index}/{id?}");
});

with attributes
[Route("[controller]")]
public class AnalyticsController : Controller
{
    [Route("Dashboard")]
    public IActionResult Index()
    {
        return View();
    }

    [Route("[action]")]
    public IActionResult Charts()
    {
        return View();
    }
}

rest
[Route("api/[controller]")]
public class ValuesController : Controller
{
    // GET api/values
    [HttpGet]
    public IEnumerable<string> Get()
    {
        return new string[] {"hello", "world!"};
    }

    // POST api/values
    [HttpPost]
    public void PostCreate([FromBody] string value)
    {
    }
}

constraints
[HttpGet("{id:int}")]
public string GetById(int id)
{
    return "item " + id;
}

.net core connect local mysql

choose mysql
local with mamp or docker
---
install
nuget
Pomelo.EntityFrameworkCore.MySql
---
in appsettings.json:

"ConnectionStrings": {
    "DefaultConnection": "server=localhost;port=3306;database=dotnetmysqltest;uid=username;password=password",
  }

setup entities
recipe.class

using System;
using System.Collections.Generic;

namespace testlocalmysql.Entities
{
    public class Recipe
    {
      
        public int RecipeId { get; set; }
        public string Name { get; set; }
       // public TimeSpan TimeToCook { get; set; } // gave error time(6) ???
// works as double
        public double TimeToCook { get; set; }
        public bool IsDeleted { get; set; }
        public string Method { get; set; }

        public ICollection<Ingredient> Ingredients { get; set; }
    }
}

ingredient.class
using System;
namespace testlocalmysql.Entities
{
    public class Ingredient
    {
        public int IngredientId { get; set; }
        public int RecipeId { get; set; }
        public string Name { get; set; }
        public decimal Quantity { get; set; }
        public string Unit { get; set; }
    }
}

register dbcontext

using System;
using Microsoft.EntityFrameworkCore;
using testlocalmysql.Entities;

namespace testlocalmysql.Db
{
    public class AppDbContext: DbContext
    {
        public AppDbContext(DbContextOptions<AppDbContext> options) : base(options)
        {
       
        }
           
        public DbSet<Recipe> Recipes { get; set; }

    }
}

add to startup.cs
            services.AddDbContext<AppDbContext>(options =>
            options.UseMySql(Configuration.GetConnectionString("DefaultConnection")));

use ef
test if works

dotnet ef --help

apply first migration
dotnet ef migrations add InitialSchema

migration folder is created with 3 new files
finish it with
dotnet ef database update

Subscribe to RSS - dotnet .net