Adding editable field to ASP.NET MVC Account model - c#

I am having trouble editing a field I have added to my account model in asp.net MVC's account model. I can create and access this field just fine, but I can't for the life of me figure out how to edit it. The value I want to be able to edit is "UserInputTwo"
Here is what my model for it looks like now:
[Table("UserProfile")]
public class UserProfile
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int UserId { get; set; }
public string UserName { get; set; }
public string FID { get; set; }
public string UserInputTwo { get; set; }
}
Here is my attempt that the View so far, but no luck:
#using (Html.BeginForm("Manage", "Account")) {
#Html.AntiForgeryToken()
#Html.ValidationSummary()
<fieldset>
<legend>Change Info Form</legend>
<ol>
<li>
#Html.LabelFor(m => m.UserInputTwo)
#Html.TextBoxFor(m => m.UserInputTwo)
</li>
</ol>
<input type="submit" value="Change password" />
</fieldset>
}
edit: here's the controller:
public ActionResult EditInfo(string user)
{
ViewBag.User = user;
return View();
}
[HttpPost]
public ActionResult EditInfo(UserProfile UserProfile)
{
if (ModelState.IsValid)
{
db.Entry(UserProfile).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Success");
}
return RedirectToAction("Success");
}

Related

.Net MVC: How to correct <Form> fields in a post request for a different data model?

How can you send a form in a POST request, to another data model (not the one in the view)?
I have UserModel and FilterRequest Models.
To filter the data do I need to post a request to an IndexFilter with a FilterRequest filtering model?
Help Please, how can I do this?
View/User/Index.cshtml
#model UserModel
#using (Html.BeginForm("IndexFilter", "User", FormMethod.Post))
{
<input type="hidden" name ="pageNumber" value="#Model.PaginationModel.PageNumber"/>
<div>
<label>First Name</label>
#Html.TextBoxFor(m => m.FilterData.FirstName)
</div>
<div>
<label>Last Name</label>
#Html.TextBoxFor(m => m.FilterData.LastName)
</div>
<input type="submit" value="Filter" />
}
UserController.cs
[HttpPost]
public IActionResult IndexFilter([FromBody] FilterRequest request)
{
}
UserModel.cs
public class UserModel
{
public IList<User> Users{ get; set; }
public PaginationModel PaginationModel { get; set; }
public FilterData FilterData { get; set; }
}
FilterRequest.cs
public class FilterRequest
{
public int PageNumber { get; set; } = 1;
public FilterData FilterData { get; set; }
}
A Post request is sent to the server, with Form Data
pageNumber=1&FilterData.FirstName=&FilterData.LastName=Nikita&__RequestVerificationToken=Token
The server replied with 415.
Change to [FromForm].
[HttpPost]
public IActionResult IndexFilter([FromForm] FilterRequest request)
{
//...
return Ok();
}
Test Code
public class UserController : Controller
{
public IActionResult Index()
{
UserModel user = new UserModel()
{
PaginationModel = new PaginationModel { PageNumber = 100 },
FilterData = new FilterData { FirstName = "Ada", LastName = "Michael" }
};
return View(user);
}
[HttpPost]
public IActionResult IndexFilter([FromForm] FilterRequest request)
{
return Ok();
}
}
Screenshot of Debugging

Delete Entry from the database onclick in C# MVC Entity framework

I am trying to delete and entry from my database by click a delete link. I am also trying to use entity framework:
Here is what I have in my controller:
public ActionResult DeleteUserUserList(string UserName)
{
using (UsersContext db = new UsersContext())
{
//var username = db.UserProfile.UserName;
db.Entry(UserName).State =
System.Data.Entity.EntityState.Deleted;
db.SaveChanges();
}
return RedirectToAction("UserList", "Account", new {UserName =
UserName});
}
Then my model looks like this:
public class UsersContext : DbContext
{
public UsersContext()
: base("DefaultConnection")
{
}
public DbSet<UserProfile> UserProfiles { get; set; }
public DbSet<Membership> Membership { get; set; }
public DbSet<Role> Roles { get; set; }
}
[Table("UserProfile")]
public class UserProfile
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int UserId { get; set; }
public string UserName { get; set; }
public string Email { get; set; }
}
And this is what my view looks like:
#model IEnumerable<ComtrexCloudReporting.Models.UserProfile>
#{
ViewBag.Title = "UserList";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2 class="admin-home-link orange-titles">#Html.ActionLink("User
Information", "AdminIndex")</h2>
<p> </p>
#foreach (var item in Model)
{
<p class=" col-sm-4 userNameUserList">#Html.DisplayFor(modelItem =>
item.UserName) </p>
<p class="col-sm-4 to-link"><span style="color: #f05322">|</span> <a
href="#string.Format("mailto:{0}",
item.Email)">#Html.DisplayFor(modelItem => item.Email)</a></p>
<p class="col-sm-4 to-link"><span style="color: #f05322">|</span> <span
onclick="return confirm('Are you sure to delete?')"><a class="back-link"
href="/Account/DeleteUserUserList?UserName=#item.UserName">Delete</a>
</p>
}
I'm getting the error that the type String is not part of the model for the current context. Does anyone know what I am doing wrong? It is breaking at this point right here: db.Entry(UserName).State = System.Data.Entity.EntityState.Deleted;
You don't have a DbSet<string> (and you can not have), thus the string is not an database entity. You need to first find you UserProfile entity:
var userProfile = context.UserProfiles.FirstOrDefault(u => u.UserName == userName);
...and then, remove it:
context.UserProfiles.Remove(userProfile);

FormMethod.Post returning 0

I have a problem with a FormMethod Post, I'm trying to post one single value (id) and store it in a Session variable, but the value return 0.
This is my code.
#foreach (var item in Model)
{
using (#Html.BeginForm("Index", "ProductSelec", FormMethod.Post))
{
#Html.HiddenFor(modelItem => item.id, new { value = "#Html.DisplayFor(modelItem => item.id)" })
<div class="AppOpt">
<button type="submit" name="submit" style="background-image: url('../Content/ICONS/SystemApp/#Html.DisplayFor(modelItem => item.img)');border-radius: 20px;background-size: cover;background-repeat: no-repeat;" class="AppImg">
<div class="OptNameRec">
<div class="OptIcon">
<img src='~/Content/ICONS/#Html.DisplayFor(modelItem => item.icon)'>
</div>
<div>
<p>#Html.DisplayFor(modelItem => item.nombre)</p>
</div>
<div class="clear"></div>
</div>
<div class="OptImage"></div>
</button>
</div>
}
}
The form is inside the foreach, becuase I'm creating the elements dinamically from a DB.
I want to store the item.id clicked.
This is my Controller
public ActionResult Index()
{
return View(db.aplicaciones.ToList());
}
public ActionResult ProductFamily()
{
return View();
}
[HttpPost]
public int Index(aplicaciones aplicaciones)
{
Session["appID"] = aplicaciones.id;
return aplicaciones.id;
}
and this is my Model.
public partial class aplicaciones
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public aplicaciones()
{
this.appNfam = new HashSet<appNfam>();
}
public int id { get; set; }
public string nombre { get; set; }
public string icon { get; set; }
public string img { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<appNfam> appNfam { get; set; }
}
I was trying to create another Model, but when I added, the foreach didn't read the values from the database.
I hope you can help me.
Change your controller method to:
[HttpPost]
public int Index(int id)
{
Session["appID"] = id;
return id;
}
Change your Html.BeginForm to be:
#using (Html.BeginForm("Index", "ProductSelec", new { id = item.id },FormMethod.Post, new { })
You should also be able to remove the hidden field since the ID will be posted by itself from your form action.

MVC Add Record to Database

Could somebody please help me add a record to a database?
I have created some base elements, but I'm struggling with the code for the AccountController. I would like for a user to enter the values for Stone and Pound via the form, and on posting add a record to the Weight table along with current Id of the logged in user and current date. Here is what I have so far.
AddWeightModel
public class AddWeightModel
{
[Required]
[DataType(DataType.Text)]
[Display(Name = "Stone")]
public Nullable<short> Stone { get; set; }
[Required]
[DataType(DataType.Text)]
[Display(Name = "Pound")]
public Nullable<short> Pound { get; set; }
}
WebApplication1Entities
public partial class WebApplication1Entities : DbContext
{
public WebApplication1Entities()
: base("name=WebApplication1Entities")
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
throw new UnintentionalCodeFirstException();
}
public virtual DbSet<Weight> Weights { get; set; }
}
Weight
public partial class Weight
{
public int Id { get; set; }
public string UserId { get; set; }
public Nullable<short> Stone { get; set; }
public Nullable<short> Pound { get; set; }
public Nullable<System.DateTime> Date { get; set; }
}
_UpdatePartial
#using Microsoft.AspNet.Identity
#model WebApplication1.Models.AddWeightModel
#using (Html.BeginForm("RecordCard", "Account", FormMethod.Post, new { #id = "contact-form", role = "form" }))
{
<fieldset>
#Html.AntiForgeryToken()
#Html.ValidationSummary()
<div class="form-div-5">
<label>
#Html.TextBoxFor(m => m.Stone, new { #placeholder = "Stone *", #type = "text" })
</label>
</div>
<div class="form-div-5">
<label>
#Html.TextBoxFor(m => m.Pound, new { #placeholder = "Pound *", #type = "text" })
</label>
</div>
<div class="button-wrapper">
<input type="submit" value="Submit" class="button" />
</div>
</fieldset>
}
AccountController
public ActionResult RecordCard()
{
var UserId = User.Identity.GetUserId();
var weightModel = from m in db.Weights where m.UserId == UserId select m;
return View(weightModel);
}
public ActionResult RecordCard(Weight Model)
{
if (ModelState.IsValid)
{
using (WebApplication1 db = new WebApplication1())
{
Weight weight = new Weight();
weight.UserId = User.Identity.GetUserId();
weight.Stone = Model.Stone;
weight.Pound = Model.Pound;
weight.Date = System.DateTime.Now;
db.Weights.Add(Model);
db.SaveChanges();
}
}
return View(Model);
}
Please note that _UpdatePartial is called from RecordCard like so:
#Html.Partial("_WeightPartial", new AddWeightModel())
And also RecordCard receives an IEnumerable list:
#model IEnumerable<Shedtember.Models.Weight>
I need a list of records from the Weight table depending on logged in user to generate a graph.
Just want to add the record and return to the RecordCard page.
Please help, I'm going insane!
I'll try to break this down.
Your compile error at:
db.Weights.Add(Model);
occurs because db.Weights.Add() expects a Weight. You are passing it your model of type AddWeightModel. You need to convert your model back to a Weight:
Weight weight = new Weight();
weight.UserId = //get your current user's ID
weight.Stone = Model.Stone;
weight.Pount = Model.Pound;
weight.Date = DateTime.UTCNow;
db.Weights.Add(weight);
Next, your method
public ActionResult RecordCard(AddWeightModel Model)
needs to be a POST, so decorate it:
[HttpPost]
public ActionResult RecordCard(AddWeightModel Model)
Now in your view you are (very correctly) adding a #Html.AntiForgeryToken(). It doesn't help you unless you validate it:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult RecordCard(AddWeightModel Model)
Step back, and examine what types you are working with.

MVC4 - Model not been passed to controller for action

I've got two models.
Model A for example contains basic get set for atrributes (i.e)
[Required]
[StringLength(100)]
[Display(Name = "Comment: ")]
public string Comment { get; set; }
public bool IsSuccess { get; set; }
Model two uses attributes in modal a, i.e
public ModelA Deposit { get; set; }
public ModelA Withdrawal { get; set; }
public ModelA Transfer { get; set; }
In my View all I am doing is using 3 forms in one page with very similar fields.
For same reason Withdrawal and transfer work with no problems. The code is almost identical in all 3
However when I am doing deposit, the ActionResult in the post is not been passed on the model.
public ActionResult Index()
{
SetViewBagAccounts();
var model = new ModelB {};
return View(model);
}
[HttpGet]
public ActionResult Deposit()
{
return View();
}
[HttpPost]
public ActionResult Deposit(ModelB model)
{
int acct = Convert.ToInt32(Request.Form["Accounts"]);
var comment = model.Deposit.Comment;// This causes **NullReferenceException**
}
The error I am getting in http post is NullReferenceExcption.
When I debug, the model being passed to the action method, Deposit, is all empty.
BELOW IS A SAMPLE OF THE VIEW
#model Login.Models.ModelB
#{
ViewBag.Title = "ATM";
}
<h2>ATM</h2>
<div id="leftpanel" style="position:absolute;left:0;width:33%;">
#using (Html.BeginForm("Deposit", "ATM", FormMethod.Post, new {}))
{
<div>
<fieldset>
<legend>Deposit Money</legend>
<div>#Html.LabelFor(u=>u.Deposit.AccountNumber1)</div>
<div>#Html.DropDownList("Accounts", "-- Select Account --")
</div>
<div>#Html.LabelFor(u=>u.Deposit.Amount)</div>
<div>#Html.TextBoxFor(u=>u.Deposit,new {style = "width:150px"})
#Html.ValidationMessageFor(u=>u.Deposit.Amount)
</div>
<div>#Html.LabelFor(u=>u.Deposit.Comment)</div>
<div>#Html.TextAreaFor(u=>u.Deposit.Comment,new {style = "width:250px"})
#Html.ValidationMessageFor(u=>u.Deposit.Comment)
</div>
<input type="submit" value ="Submit" style="width:31%;"/>
<input type="reset" value ="Clear" style="width:31%;"/>
</fieldset>
</div>
}
The div for deposit is pretty much copied again for withdrawal and transfer, only changed bit is :
#using (Html.BeginForm("Withdrawal", "ATM", FormMethod.Post, new {}))
#using (Html.BeginForm("Transfer", "ATM", FormMethod.Post, new {}))

Categories

Resources