i want to add URL #Context.Request.Query for take URL automation fill in to textbox. but when i add URL #Context.Request.Query[] for automation which column data will disapper. for example, when i automation Textbox[Name],[ID] and not tick IsAccept and go to sumbit. the column[Name] and[ID] will Disappear. but if i cancel use #Context.Request.Query[]. it is normal. For example, i manually input the data to Textbox[Name],[ID] and not tick IsAccept and go to sumbit. the column[Name] and[ID] will sill keep all data.
anybody can give advise and help??thank so much!
Controller
public class CheckBoxRequired : ValidationAttribute
{
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
//get the entered value
var student = (UserViewModel)validationContext.ObjectInstance;
//Check whether the IsAccepted is selected or not.
if (student.IsAccepted == false)
{
return new ValidationResult(ErrorMessage == null ? "Please checked the checkbox" ErrorMessage);
}
return ValidationResult.Success;
}
}
Controller
public IActionResult CreateUser()
{
return View();
}
[HttpPost]
public IActionResult CreateUser(UserViewModel user)
{
if (ModelState.IsValid)
{
//after validation success, create a UserClass instance based on the ViewModel, and insert the "newuser" into database.
var newuser = new UserClass();
newuser.ID = user.ID;
newuser.Name = user.Name;
//save the newuser into the database via dbcontext
_dbcontext.UserClass.Add(newuser);
_dbcontext.SaveChanges();
return RedirectToAction(nameof(Index));
}
return View();
}
View:
#model WebApplication2.Models.UserViewModel
#{
ViewData["Title"] = "CreateUser";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<div class="row">
<div class="col-md-6">
<form asp-action="CreateUser">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="ID" class="control-label"></label>
<input asp-for="ID" class="form-control"value="#Context.Request.Query["ID"]" />
<span asp-validation-for="ID" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Name" class="control-label"></label>
<input asp-for="Name" class="form-control"
value="#Context.Request.Query["Name"]"/>
<span asp-validation-for="Name" class="text-danger"></span>
</div>
<div class="form-group form-check">
<label class="form-check-label">
<input class="form-check-input" asp-for="IsAccepted" />
</label>
<span asp-validation-for="IsAccepted" class="text-danger"></span>
</div>
<div class="form-group">
<input type="submit" value="Create" class="btn btn-primary" />
</div>
</form>
</div>
</div>
Models
public class UserViewModel
{
[Required(ErrorMessage = "Entry ID")]
public int ID { get; set; }
[Required(ErrorMessage = "Entry Name")]
public string Name { get; set; }
//use custom validation method
[CheckBoxRequired(ErrorMessage ="Please checked the items")]
public bool IsAccepted { get; set; }
}
According to what you told me in the comments, I highly recommend you to do it this way in the controller you should change it to look this way
[HttpGet]
public IActionResult CreateUser(string name)
{
return View();
}
Then you have 2 options,
you fill up a viewmodel and you send it to the view, or option number
[HttpGet]
public IActionResult CreateUser(string name)
{
UserViewModel vm = new UserViewModel { Name = name };
return View(vm);
}
In the view replace value="#Context.Request.Query["Name"]" with this value="#Model.Name"
You fill the viewbag and then consume it on the View
[HttpGet]
public IActionResult CreateUser(string name)
{
ViewBag.Name = name;
return View();
}
In the view replace value="#Context.Request.Query["Name"]" with this value="#(ViewBag.Name as string)"
It could actually work without the casting the ViewBag in this particular case so it could be only value="#ViewBag.Name"
GIF1:
https://i.stack.imgur.com/qGrwz.gif
GIF1: When i add value="#Context.Request.Query["Name"]" to input asp-for="Name" class="form-control".
it will cause all column data disappear.
GIF2
https://i.stack.imgur.com/vGmHU.gif
it is my target when i add i add value="#Context.Request.Query["Name"]" to input asp-for="Name" class="form-control".
all the column data should keep
Thanks!
Related
I have a C# ASP.Net Core MVC Web-Application and I want to make two forms, where I can input a Model. My problem is, one of both work and the other one don't, and I don't understand why.
When I'm saying it doesn't work, I mean, that I get a null value in my LogInWordForm method and the one who works gets the value from the input of the form.
(To add [HTTPPOST] in the controller and method="post" in the cshtml I already tried)
First of all my controller for both [GameController.cs -> C#]:
public class GameController : Controller
{
// ToDo: Aus Singleton es machen, dass es auf User session bezogen ist.
private readonly ILogger<HomeController> _logger;
private Wheelchair instance;
public SimpleGameUser sgu;
public static string moneySession = "_money";
public static string questionSession = "_qanda";
// true : false
public IActionResult LogInWord()
{
if (!CheckSession()) return RedirectToAction("Index", "Home");
return View();
}
public IActionResult LogInWordForm(Word word)
{
if (!CheckSession()) return RedirectToAction("Index", "Home");
if (ModelState.IsValid)
{
string solution = this.sgu.wheelchair.word;
solution = solution.Replace("[", string.Empty);
solution = solution.Replace("]", string.Empty);
solution = solution.Replace("_", " ");
if (word.word.Equals(solution))
return View("GameOver", this.sgu);
else
{
ViewBag.Fail = "Word wasn't guessed.";
return View("WheelSpin", this.instance);
}
}
return View("LogInWord", word);
}
public IActionResult QuestionAndAnswer()
{
return CheckSession() ? View() : RedirectToAction("Home", "Index");
}
public IActionResult QAnswered(QandA qanda)
{
if (!CheckSession()) return RedirectToAction("Index", "Home");
if (sgu.money < qanda.risk)
{
ModelState.AddModelError("risk", "You haven't enough money to risk this!");
}
if (ModelState.IsValid)
{
if(qanda.userAnswer.Equals(qanda.variant))
{
this.sgu.money += qanda.risk;
} else
{
this.sgu.money -= qanda.risk;
}
HttpContext.Session.SaveObject<SimpleGameUser>(sgu, HomeController.userNow);
return WheelSpin();
}
return View("QuestionAndAnswer", qanda);
}
private bool CheckSession()
{
this.sgu = HttpContext.Session.GetObject<SimpleGameUser>(sessionName: HomeController.userNow);
this.instance = sgu.wheelchair;
return sgu != default;
}
Model of the first one who's not working [Word.cs -> C#]:
public class Word : IValidatableObject
{
[Required(ErrorMessage = "This field is required!")]
[Display(Name = "Your word to Log In")]
public string word { get; set; }
public string errors { get; set; } = ";";
public Word()
{
}
public Word(string word)
{
this.word = word;
}
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
List<ValidationResult> errors = new List<ValidationResult>();
List<Char> letters = Consonant.consonants;
letters.AddRange(Consonant.vocals);
letters.Add(',');
letters.Add('.');
letters.Add('_');
if (!letters.Any(s => this.word.Contains(s)))
errors.Add(new ValidationResult("There was an illegal character"));
return errors;
}
}
if someone wants to know: the validation should be testing if there are only characters and some allowed letters used, what I couldn't test yet.
View [LongInWord.cshtml]:
#model Word;
#{
}
<div id="layoutAuthentication_content">
<div class="container">
<div class="row justify-content-center">
<div class="col-lg-5">
<div class="card shadow-lg border-0 rounded-lg mt-5">
<div class="card-header"><h3 class="text-center font-weight-light my-4">Login</h3></div>
<div class="card-body">
<form asp-action="LogInWordForm" asp-controller="Game">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-floating mb-3">
<input asp-for="word" type="text" />
<label asp-for="word"></label>
<span asp-validation-for="word" class="text-danger"></span>
</div>
<br />
<input class="btn btn-primary" type="submit" />
</form>
</div>
</div>
</div>
</div>
</div>
</div>
Now of the one which is working:
Model [QandA.cs -> C#]:
public class QandA
{
public int ID { get; set; }
[BindProperty, Required(ErrorMessage = "This field can't be empty!")]
[Range(0, 1, ErrorMessage = "This wasn't one of the two given answers...")]
public bool userAnswer { get; set; }
public string question { get; set; }
public string answer0 { get; set; }
public string answer1 { get; set; }
public bool variant { get; set; }
[Required(ErrorMessage = "This field can't be empty!")]
[Range(0, int.MaxValue, ErrorMessage = "Please enter valid positiv integer Number above 0")]
[Display(Name = "Select your risk")]
public int risk { get; set; }
public QandA(string question, string answer0, string answer1, bool variant)
{
this.question = question;
this.answer0 = answer0;
this.answer1 = answer1;
this.variant = variant;
}
public QandA()
{
}
public bool correctAnswered()
{
return this.variant == this.userAnswer;
}
}
View [QuestionAndAnswer.cshtml]:
#model QandA;
#{
}
<div id="layoutAuthentication_content">
<div class="container">
<div class="row justify-content-center">
<div class="col-lg-5">
<div class="card shadow-lg border-0 rounded-lg mt-5">
<div class="card-header"><h3 class="text-center font-weight-light my-4">Login</h3></div>
<div class="card-body">
<form asp-action="QAnswered" asp-controller="Game">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<h3>#Model.question </h3>
<div class="form-group">
<label asp-for="userAnswer">Example select</label>
<div class="form-control">
<input asp-for="userAnswer" type="radio" class="btn-check" name="options-outlined" id="success-outlined" autocomplete="off" value="0" checked>
<label class="btn btn-outline-success form-control" for="success-outlined">#Model.answer0</label>
<input asp-for="userAnswer" type="radio" class="btn-check" name="options-outlined" id="danger-outlined" autocomplete="off" value="1">
<label class="btn btn-outline-danger form-control" for="danger-outlined">#Model.answer1</label>
</div>
</div>
<br />
<div class="form-group">
<label asp-for="risk"></label>
<input type="number" min="0" class="form-control" />
<span asp-validation-for="risk" class="text-danger"></span>
</div>
<input class="btn btn-primary" type="submit" />
</form>
</div>
</div>
</div>
</div>
</div>
</div>
The model binding doesn't know how to bind this. You have a parameter named word and in the type of the parameter you have a property with the same name.
public class GameController : Controller
{
// ...
// here you have a parameter named word, and in the model type you have a property named the same way
// rename the parameter to something elese - for ex. formData
public IActionResult LogInWordForm(Word word)
{
// ...
}
// ...
}
Here is the code for Edit:
[HttpGet]
public async Task<IActionResult> Edit(string id)
{
var roles = _roleManager.Roles.ToList();
ViewBag.Roles = new SelectList(roles, "Id", "Name");
ApplicationUser user = await _userManager.FindByIdAsync(id);
if (user == null)
{
ViewBag.ErrorMessage = $"User with Id = {id} cannot be found";
return NotFound();
}
var userRole = _userManager.GetRolesAsync(user).ToString();
var userViewModel = new EditUserViewModel
{
UserId=user.Id,
Username=user.UserName,
FirstName=user.FirstName,
LastName=user.LastName,
Email=user.Email,
UserPIN=user.UserPIN,
Address=user.Address,
TelephoneNumber=user.PhoneNumber,
Roles = userRole
};
return View(userViewModel);
}
[HttpPost]
public async Task<IActionResult> Edit(EditUserViewModel userViewModel)
{
var user = await _userManager.FindByIdAsync(userViewModel.UserId);
if (user == null)
{
ViewBag.ErrorMessage = $"User with Id = {userViewModel.UserId} cannot be found";
return NotFound();
}
else
{
user.UserName = userViewModel.Username;
user.FirstName = userViewModel.FirstName;
user.LastName = userViewModel.LastName;
user.Email = userViewModel.Email;
user.UserPIN = userViewModel.UserPIN;
user.Address = userViewModel.Address;
user.PhoneNumber = userViewModel.TelephoneNumber;
var result = await _userManager.UpdateAsync(user);
_dbContext.SaveChanges();
if (result.Succeeded)
{
return RedirectToAction("Index");
}
foreach (var error in result.Errors)
{
ModelState.AddModelError("", error.Description);
}
return View(userViewModel);
}
}
This is my view model for Edit:
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
namespace Project.Models.UserViewModels
{
public class EditUserViewModel
{
public string UserId { get; set; }
[Required]
[StringLength(50, MinimumLength = 6,
ErrorMessage = "Username cannot be shorter than 6 characters and longer than 50.")]
public string Username { get; set; }
[Required]
public string FirstName { get; set; }
[Required]
public string LastName { get; set; }
[Required]
[EmailAddress]
[Display(Name = "Email")]
public string Email { get; set; }
[Required]
[StringLength(10, MinimumLength = 10,
ErrorMessage = "User PIN must be 10 characters long")]
public string UserPIN { get; set; }
[Required]
[StringLength(10, MinimumLength = 10,
ErrorMessage = "Telephone number must be 10 characters long")]
public string TelephoneNumber { get; set; }
[Required]
public string Address { get; set; }
[Required]
public string Roles { get; set; }
}
}
And this is my View:
#model Project.Models.UserViewModels.EditUserViewModel
<h1>Edit User</h1>
<div class="col-md-4">
<form asp-action="Edit" asp-controller="Admin" method="post">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="FirstName"> First name</label>
<input asp-for="FirstName" class="form-control" />
<span asp-validation-for="FirstName" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="LastName"> Last name</label>
<input asp-for="LastName" class="form-control" />
<span asp-validation-for="LastName" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Username"> Username</label>
<input asp-for="Username" class="form-control" />
<span asp-validation-for="Username" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="UserPIN">User PIN</label>
<input asp-for="UserPIN" class="form-control" />
<span asp-validation-for="UserPIN" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Email"></label>
<input asp-for="Email" class="form-control" />
<span asp-validation-for="Email" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="TelephoneNumber"></label>
<input asp-for="TelephoneNumber" class="form-control" />
<span asp-validation-for="TelephoneNumber" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Roles">Role</label>
<select asp-for="Roles" class="form-control" asp-items="#ViewBag.Roles"></select>
<span asp-validation-for="Roles" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Address">Address</label>
<input asp-for="Address" class="form-control" />
<span asp-validation-for="Address" class="text-danger"></span>
</div>
<div class="form-group">
<input type="submit" value="Save" class="btn btn-primary" />
</div>
</form>
</div>
<div>
<a asp-action="Index">Back to User list</a>
</div>
I create an asp.net core application using Identity. Now I am customizing the project. I wrote AddUser and role and Delete Actions and they are working.
I get HTTP ERROR 404 exception when I try to edit my user in UserList.
I add _dbContext.SaveChanges(), but it is still not working. The rest CRUD operations are working properly like I said earlier.
The code that saves your model depends on the presence of the userViewModel.UserId information. But this is not present in the .cshtml code. So when the model is passed back to the controller in the HttpPost there is no data and the _userManager.FindByIdAsync will not find any user. The fix is simple, just add somewhere in the .cshtml an hidden field for the UserId
<form asp-action="Edit" asp-controller="Admin" method="post">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div> <input asp-for="UserId" class="d-none" /></div>
....
It is an hard fact to remember that the istance of the ViewModel passed to the view from the HttpGet action is not the same instance passed back to the HttpPost action. It is a new ViewModel instance and it is populated from the fields present in the View. If you forget a field then there is no value in the model passed back to the post action.
You have a fairly explicit error there in that 404 NotFound.
There's either a mismatch between how you're creating and storing the user, or in how you're attempting to retrieve it from _userManager, particularly:
_userManager.FindByIdAsync(userViewModel.UserId)
When debugging the Edit action, does the view model property UserId have a value?
If so, does the value match what UserId is set to when the user is created?
Either modify the data at creation, or supply more data during editing, to create a succesful match
Product Model Class
public class Product
{
public Guid ProductId { get; set; }
public string Name { get; set; }
}
Home Controller:
public class HomeController : Controller
{
[HttpGet]
public IActionResult EditProduct()
{
Product product = new Product()
{
ProductId = Guid.Empty,
Name = "Abc"
};
return View(product);
}
[HttpPost]
public IActionResult EditProduct(Product product)
{
Product productCopy = new Product()
{
ProductId = Guid.NewGuid(),
Name = product.Name + "d"
};
return View("EditProductCopy", productCopy);
}
}
EditProduct View
Note: Auto Generated from Product Model Class,
EditProductCopy is similar, only title is different
#model WebApplicationTest.Models.Product
#{
ViewData["Title"] = "EditProductCopy";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h1>EditProductCopy</h1>
<h4>Product</h4>
<hr />
<div class="row">
<div class="col-md-4">
<form asp-action="EditProduct">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="ProductId" class="control-label"></label>
<input asp-for="ProductId" class="form-control" />
<span asp-validation-for="ProductId" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Name" class="control-label"></label>
<input asp-for="Name" class="form-control" />
<span asp-validation-for="Name" class="text-danger"></span>
</div>
<div class="form-group">
<input type="submit" value="Save" class="btn btn-primary" />
</div>
</form>
</div>
</div>
<div>
<a asp-action="Index">Back to List</a>
</div>
I call "EditProduct" view. I don't change anything and I click the "Save" button. "EditProductCopy" view is rendered and I expect to see that new ProductId and "Abcd" as Product name. But I see last posted data (ProductId is empty guid and Name is "abc") What is the reason of this problem?
Project Files can be downloaded from this link:
Project Files
Default TagHelper display ModelState value not Model.Just add ModelState.Clear() before you return View:
[HttpPost]
public IActionResult EditProduct(Product product)
{
Product productCopy = new Product()
{
ProductId = Guid.NewGuid(),
Name = product.Name + "d"
};
ModelState.Clear();//add this line...
return View("EditProductCopy", productCopy);
}
Result:
The request is submitted with GET method because method attribute of the form is not specified. So, write method="POST" in the form.
The problem is when I try to update Master and Details Tables at the same time.
When call Post Edit Task the Details objects don´t appear.
The Edit View displays all Details rows correctly, but while debugging the Edit POST, Casas is empty
MODELS
public partial class Modelo : IValidatableObject {
public Modelo()
{
Casas = new HashSet<Casa>();
}
public int Modeloid { get; set; }
public string Modelo1 { get; set; }
public virtual ICollection<Casa> Casas { get; set; }//Don’t work to update
}
public partial class Casa // DETAIL TABLE
{
public int Casaid { get; set; }
public int Modeloid { get; set; } // FK to Modelo
public string Casa1 { get; set; }
public virtual Modelo Modelo { get; set; }
}
CONTROLLER
public class ModelosController : Controller
. . . . . . . . .
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(int id, Modelo modelo)
{
if (id != modelo.Modeloid)
{
return NotFound();
}
if (ModelState.IsValid)
{
// Here modelo.Modelo1 has current modified value
// but modelo.Casas.Count == 0
_context.Update(modelo);
await _context.SaveChangesAsync();
}
}
// GET: Modelos/Edit
public async Task<IActionResult> Edit(int? id)
{
if (id == null)
{
return NotFound();
}
var modelo = await _context.Modelo
.AsNoTracking()
.Include(m => m.Fotomodelos)
.Include(m => m.Casas)
.SingleOrDefaultAsync(m => m.Modeloid == id);
if (modelo == null)
{
return NotFound();
}
return View(modelo);
}
View EDIT.CSHTML
#using System.IO
#model Disponibilidad.Models.Modelo
<form asp-action="Edit">
<div class="form-horizontal">
<hr />
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<input type="hidden" asp-for="Modeloid" />
<div class="form-group">
<label asp-for="Modelo1" class="col-md-2 control-label"></label>
<div class="col-md-10">
<input asp-for="Modelo1" class="form-control" />
<span asp-validation-for="Modelo1" class="text-danger"></span>
</div>
</div>
#{
for (int i = 0; i < Model.Casas.Count; i++)
{
<input type="hidden" asp-for="#Model.Casas.ElementAt(i).Modeloid"
value="#Model.Modeloid" />
<input type="hidden" asp-for="#Model.Casas.ElementAt(i).Casaid" />
<div class="form-group">
<label asp-for="#Model.Casas.ElementAt(i).Casa1"
class="col-md-2 control-label"></label>
<div class="col-md-10">
<input asp-for="#Model.Casas.ElementAt(i).Casa1"
class="form-control" /> <!-- DISPLAY OK Detail rows -->
<span asp-validation-for="#Model.Casas.ElementAt(i).Casa1"
class="text-danger"></span>
</div>
</div>
}
}
<div class="btn-group">
<button type="submit" class="btn btn-danger">Save</button>
</div>
</div>
</form>
When you use a for cycle instead of foreach in Razor, the name of the properties doesn't get rendered correctly when using the default asp-for TagHelpers.
You can correct your example changing your razor form inputs as follow:
From:
<input type="hidden" asp-for="#Model.Casas.ElementAt(i).Casaid" />
To:
<input type="hidden" name="modelo.Casas[#i].Casaid" value="#Model.Casas.ElementAt(i).Casaid" />
I have a simple Web application in ASP.NET MVC 6 RC1.
The problem is that when editing a previously added item. The item returned to the Edit POST has an ID = 0, so it creates a copy of the data I was trying to update.
When pressing the Edit link, it takes me to the correct route:
http://localhost:41250/Proyectos/Edit/1
And the GET IActionResult recieves the correct id.
But inside the edit form, when I press the Save button, in the Controller POST part of the Edit it recieves a proyecto who has all the data from the form except the id (ProyectoId) which is 0.
Model:
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
namespace RegistroHora.Models
{
public class Proyecto
{
[ScaffoldColumn(false)]
[Key]
public int ProyectoId { get; set; }
[Required]
public string Nombre { get; set; }
[Required]
[Display(Name ="Número de Horas")]
public decimal NumHoras { get; set; }
[Required]
[Display(Name = "Tipo de Horas")]
public string TipoHoras { get; set; }
[Display(Name = "Proyecto Finalizado")]
public bool Concluido { get; set; }
public virtual ICollection<Registro> Registros { get; set; }
}
}
View:
#model RegistroHora.Models.Proyecto
#{
ViewData["Title"] = "Edit";
}
<h2>Edit</h2>
<form asp-action="Edit">
<div class="form-horizontal">
<h4>Proyecto</h4>
<hr />
<div asp-validation-summary="ValidationSummary.ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="Nombre" class="col-md-2 control-label"></label>
<div class="col-md-10">
<input asp-for="Nombre" class="form-control" />
<span asp-validation-for="Nombre" class="text-danger" />
</div>
</div>
<div class="form-group">
<label asp-for="NumHoras" class="col-md-2 control-label"></label>
<div class="col-md-10">
<input asp-for="NumHoras" class="form-control" />
<span asp-validation-for="NumHoras" class="text-danger" />
</div>
</div>
<div class="form-group">
<label asp-for="TipoHoras" class="col-md-2 control-label"></label>
<div class="col-md-10">
<input asp-for="TipoHoras" class="form-control" />
<span asp-validation-for="TipoHoras" class="text-danger" />
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<div class="checkboxs">
<input asp-for="Concluido" type="checkbox"> #Html.DisplayNameFor(i => i.Concluido)
</div>
</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 {
<script src="~/lib/jquery/dist/jquery.min.js"></script>
<script src="~/lib/jquery-validation/dist/jquery.validate.min.js"></script>
<script src="~/lib/jquery-validation-unobtrusive/jquery.validate.unobtrusive.min.js"></script>
}
Controller:
using System.Linq;
using Microsoft.AspNet.Mvc;
using Microsoft.AspNet.Mvc.Rendering;
using Microsoft.Data.Entity;
using RegistroHora.Models;
namespace RegistroHora.Controllers
{
public class ProyectosController : Controller
{
private ApplicationDbContext _context;
public ProyectosController(ApplicationDbContext context)
{
_context = context;
}
// GET: Proyectos
public IActionResult Index()
{
return View(_context.Proyecto.ToList());
}
// GET: Proyectos/Details/5
public IActionResult Details(int? id)
{
if (id == null)
{
return HttpNotFound();
}
Proyecto proyecto = _context.Proyecto.Single(m => m.ProyectoId == id);
if (proyecto == null)
{
return HttpNotFound();
}
return View(proyecto);
}
// GET: Proyectos/Create
public IActionResult Create()
{
return View();
}
// POST: Proyectos/Create
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult Create(Proyecto proyecto)
{
if (ModelState.IsValid)
{
_context.Proyecto.Add(proyecto);
_context.SaveChanges();
return RedirectToAction("Index");
}
return View(proyecto);
}
// GET: Proyectos/Edit/5
public IActionResult Edit(int? id)
{
if (id == null)
{
return HttpNotFound();
}
Proyecto proyecto = _context.Proyecto.Single(m => m.ProyectoId == id);
if (proyecto == null)
{
return HttpNotFound();
}
return View(proyecto);
}
// POST: Proyectos/Edit/5
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult Edit(Proyecto proyecto)
{
if (ModelState.IsValid)
{
_context.Update(proyecto);
_context.SaveChanges();
return RedirectToAction("Index");
}
return View(proyecto);
}
// GET: Proyectos/Delete/5
[ActionName("Delete")]
public IActionResult Delete(int? id)
{
if (id == null)
{
return HttpNotFound();
}
Proyecto proyecto = _context.Proyecto.Single(m => m.ProyectoId == id);
if (proyecto == null)
{
return HttpNotFound();
}
return View(proyecto);
}
// POST: Proyectos/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public IActionResult DeleteConfirmed(int id)
{
Proyecto proyecto = _context.Proyecto.Single(m => m.ProyectoId == id);
_context.Proyecto.Remove(proyecto);
_context.SaveChanges();
return RedirectToAction("Index");
}
}
}
I have NO problem with Index, Create, Delete or Details, only Edit.
You need to pass the ProyectoId value from your form. You may keep that in a hidden field inside your form.
<form asp-action="Edit">
<input type="hidden" asp-for="ProyectoId" />
<!-- Your existing form fields for other properties goes here -->
<input type="submit" value="Save" class="btn btn-default" />
</form>
Another approach is to change signature for method Edit, like this:
public IActionResult Edit(int id, Proyecto proyecto)
In this case, you can pass id over action URL. In this case you need to modify action URL in your view as:
<form asp-action="Edit" asp-route-id=#Model.ProyectoId>
Of cource, you need proper Route that support Id as parametar.
P.s. Id you prefere the first approach, just remove [ScaffoldColumn(false)] from your property class.
Since the update in edit is around the key(ProyectoId); you cannot change it; however instead of making it will disappear by