MVC- need help for creating "Edit" View - asp.net-mvc

need help about creating Edit view. I made create view and I need to be able to edit my entry sometimes. I used entity framework for connect with sql.
```
public ActionResult Create()
{
List<Country> CountryList = db.Countries.ToList();
ViewBag.CountryList = new SelectList(CountryList, "CountryId", "CountryName");
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(CountryStateContactViewModel csvm)
{
if (!ModelState.IsValid)
{
return View(csvm);
}
Contact model = new Contact() { CountryId = csvm.CountryId, StateId = csvm.StateId, ContactId = csvm.ContactId, ImeOsobe = csvm.ImeOsobe, PrezimeOsobe = csvm.PrezimeOsobe, Komentar = csvm.Komentar, Email = csvm.Email, Aktivan = csvm.Aktivan, kcbr = csvm.kcbr, KucniBroj = csvm.KucniBroj, NazivUlice = csvm.NazivUlice, NazivNaselja = csvm.NazivNaselja, PostanskiBroj = csvm.PostanskiBroj, KontaktBroj = csvm.KontaktBroj };
db.Contacts.Add(model);
try
{
db.SaveChanges();
}
catch (System.Data.Entity.Validation.DbEntityValidationException db)
{
Exception raise = db;
foreach (var validationErrors in db.EntityValidationErrors)
{
foreach (var validationError in validationErrors.ValidationErrors)
{
string message = string.Format("{0}:{1}",
validationErrors.Entry.Entity.ToString(),
validationError.ErrorMessage);
raise = new InvalidOperationException(message, raise);
}
}
throw raise;
}
return RedirectToAction("Index");
This is Create View where I am adding new Contact from CountryStateContactViewModel (All three tables in one VIEW with 2 connected dropdown lists )
#model AkvizicijeApp_4_2.Models.CountryStateContactViewModel
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>CountryStateContactViewModel</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.CountryId, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.CountryId, ViewBag.CountryList as SelectList, "--Select
Country--", new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.CountryId, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.StateId, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.StateId, new SelectList(" "), "--Select State--", new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.StateId, "", new { #class = "text-danger" })
</div>
<div class="form-group">
#Html.LabelFor(model => model.ContactId, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.ContactId, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.ContactId, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.PostanskiBroj, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.PostanskiBroj, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.PostanskiBroj, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.NazivNaselja, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.NazivNaselja, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.NazivNaselja, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.NazivUlice, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.NazivUlice, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.NazivUlice, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.KucniBroj, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.KucniBroj, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.KucniBroj, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.kcbr, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.kcbr, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.kcbr, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Aktivan, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
<div class="checkbox">
#Html.EditorFor(model => model.Aktivan)
#Html.ValidationMessageFor(model => model.Aktivan, "", new { #class = "text-danger" })
</div>
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.ImeOsobe, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.ImeOsobe, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.ImeOsobe, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.PrezimeOsobe, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.PrezimeOsobe, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.PrezimeOsobe, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.KontaktBroj, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.KontaktBroj, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.KontaktBroj, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Email, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Email, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Email, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Komentar, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Komentar, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Komentar, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
}
<div>
#Html.ActionLink("Back to List", "Index")
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
<script src="~/Scripts/jquery-3.3.1.min.js"></script>
<script>
$(document).ready(function () {
$("#CountryId").change(function () {
$.get("/Home/GetStateList", { CountryId: $("#CountryId").val() }, function (data) {
$("#StateId").empty();
$.each(data, function (index, row) {
$("#StateId").append("<option value='" + row.StateId + "'>" + row.StateName + "
</option>")
});
});
})
});
</script>
And finally CountryStateContactViewModel, Where is id-s from first 2 tables(dropdowns) and all fields from third table.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace AkvizicijeApp_4_2.Models
{
public class CountryStateContactViewModel
{
public int CountryId { get; set; }
public int StateId { get; set; }
public int ContactId { get; set; }
public int PostanskiBroj { get; set; }
public string NazivNaselja { get; set; }
public string NazivUlice { get; set; }
public string KucniBroj { get; set; }
public string kcbr { get; set; }
public bool Aktivan { get; set; }
public string ImeOsobe { get; set; }
public string PrezimeOsobe { get; set; }
public string KontaktBroj { get; set; }
public string Email { get; set; }
public string Komentar { get; set; }
}
}
Pls help me from that code (from Create View) to make Edit View (Where I can change entries
)
Thanks alot. ;)

Edit view is almost the same... the only missing property is Id:
public class EditStateContactViewModel : CountryStateContactViewModel
{
public int Id {get;set;}
}
public ActionResult Edit(int Id)
{
List<Country> CountryList = db.Countries.ToList();
ViewBag.CountryList = new SelectList(CountryList, "CountryId", "CountryName");
ViewBag.Id = Id;
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(EditStateContactViewModel csvm)
{
if (!ModelState.IsValid)
return View(csvm);
var item = db.Contacts.First(x=>x.Id = csvm.Id);
item.CountryId = csvm.CountryId;
item.StateId = csvm.StateId;
item.ImeOsobe = csvm.ImeOsobe;
item.PrezimeOsobe= csvm.PrezimeOsobe;
item.Komentar = csvm.Komentar ;
item.Email = csvm.Email;
item.Aktivan = csvm.Aktivan ;
item.kcbr = csvm.kcbr;
item.KucniBroj = csvm.KucniBroj;
item.NazivUlice = csvm.NazivUlice ;
item.NazivNaselja = csvm.NazivNaselja ;
item.PostanskiBroj = csvm.PostanskiBroj ;
item.KontaktBroj = csvm.KontaktBroj ;
db.Contacts.Update(item);
try
{
db.SaveChanges();
}
catch (System.Data.Entity.Validation.DbEntityValidationException db)
{
Exception raise = db;
foreach (var validationErrors in db.EntityValidationErrors)
{
foreach (var validationError in validationErrors.ValidationErrors)
{
string message = string.Format("{0}:{1}",
validationErrors.Entry.Entity.ToString(),
validationError.ErrorMessage);
raise = new InvalidOperationException(message, raise);
}
}
throw raise;
}
return RedirectToAction("Index");
And View:
#model AkvizicijeApp_4_2.Models.EditStateContactViewModel
#using (Html.BeginForm())
{
#Html.HiddenFor(x=>x.Id)
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Edit CountryStateContactViewModel</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.CountryId, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.CountryId, ViewBag.CountryList as SelectList, "--Select
Country--", new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.CountryId, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.StateId, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.StateId, new SelectList(" "), "--Select State--", new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.StateId, "", new { #class = "text-danger" })
</div>
#section Scripts
{
#Scripts.Render("~/bundles/jqueryval")
}
<script src="~/Scripts/jquery-3.3.1.min.js"></script>
<script>
$(document).ready(function () {
$("#CountryId").change(function () {
$.get("/Home/GetStateList", { CountryId: $("#CountryId").val() }, function (data) {
$("#StateId").empty();
$.each(data, function (index, row) {
$("#StateId").append("<option value='" + row.StateId + "'>" + row.StateName + "
</option>")
});
});
})
});
</script>

Related

Why when Check if the user already exists in ASP.NET MVC database first not working?

I checked more than one post in this site and tried more than one solution but still I cannot check the user exist or not when register new user , I tried the following code :
[HttpPost]
public ActionResult register(Registration reg)
{
if (ModelState.IsValid)
{
var userexist = db.Registration.Any(x => x.username == reg.username);
if (userexist)
{
ModelState.AddModelError("username", "User with this name already exists");
return View(reg);
}
else
{
db.Registration.Add(reg);
db.SaveChanges();
return RedirectToAction("Index");
}
}
return View();
}
this is registration model :
namespace registration.Models
{
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
public partial class Registration
{
public int Userid { get; set; }
[Required]
[Display(Name ="ID or Iqama No ")]
public string username { get; set; }
[Required]
[Display(Name = "Medical Record Number ")]
public int PatientNo { get; set; }
[Required]
[Display(Name = "Mobile ")]
public string Mobile { get; set; }
[Display(Name = "Email Address ")]
[DataType(DataType.EmailAddress)]
public string Email { get; set; }
[Required]
[DataType(DataType.Password)]
public string Password { get; set; }
}
this is the view code and submit button there create button:
#model registration.Models.Registration
#{
ViewBag.Title = "Register New User";
}
<h2>register</h2>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Registration Window</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.username, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10" >
#Html.EditorFor(model => model.username, new { htmlAttributes = new { #type = "number", #min = "0", #value = "0", #class = "form-control" } })
#Html.ValidationMessageFor(model => model.username, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.PatientNo, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.PatientNo, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.PatientNo, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Mobile, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Mobile, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Mobile, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Email, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Email, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Email, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Password, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Password, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Password, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
}
<div>
#Html.ActionLink("Back to List", "Login")
</div>
what is the missing in my code why its not working when click enter or tab or by mouse click its not checking ?
Your code correct and no errors ,
You said
"when click enter or tab or by mouse click its not checking ?"
This code will work when you click the button Submit or Create .
The code will validate the username exist or not and not when you navigate grom the username field.
Try this:
#using (Html.BeginForm("register", "YourControllerName", FormMethod.Post, new { #id = "LoginForm", #autocomplete = "off"}))
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Registration Window</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.username, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10" >
#Html.EditorFor(model => model.username, new { htmlAttributes = new { #type = "number", #min = "0", #value = "0", #class = "form-control" } })
#Html.ValidationMessageFor(model => model.username, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.PatientNo, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.PatientNo, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.PatientNo, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Mobile, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Mobile, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Mobile, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Email, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Email, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Email, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Password, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Password, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Password, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
}
Controller:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult register(Registration reg)
{
if (ModelState.IsValid)
{
var userexist = db.Registration.Any(x => x.username == reg.username);
if (userexist)
{
ModelState.AddModelError("username", "User with this name already exists");
return View(reg);
}
else
{
db.Registration.Add(reg);
db.SaveChanges();
return RedirectToAction("Index");
}
}
return View();
}

POST form in MVC - No Values being written to DB

I have a model that I'm trying to edit with a form:
public class Basiclife
{
[Key]
public int Id { get; set; }
public int? ResponseId { get; set; }
public string Plantype { get; set; }
public int Enrolledftes { get; set; }
public decimal Pctemployer { get; set; }
public decimal Fixedbenamt { get; set; }
public decimal Salarymult { get; set; }
public decimal Bencap { get; set; }
}
And a view wrapper to edit it (with the editor in a separate partial view):
<h2>CreateBasicLifeResponse</h2>
<div id="planList">
#using (Html.BeginForm("CreateBasicLifeResponse", "Surveys"))
{
<div id="editorRows">
#foreach (var item in Model.basiclives)
{
#Html.Partial("_BasicLifeResponse", item)
}
</div>
#Html.ActionLink("Add", "BasicLifeResponse", null, new { id = "addItem", #class = "button" });
<input type="submit" value="submit" />
}
</div>
The wrapper's model is:
public class ResponseBasicLife
{
public Response response { get; set; }
public List<Basiclife> basiclives { get; set; }
}
Here's the partial view:
#using CustomSurveyTool.Models
#model Basiclife
<div class="editorRow">
#using (Html.BeginCollectionItem("basiclives"))
{
<div class="form-horizontal">
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.Plantype, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Plantype, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Plantype, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Enrolledftes, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Enrolledftes, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Enrolledftes, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Pctemployer, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Pctemployer, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Pctemployer, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Fixedbenamt, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Fixedbenamt, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Fixedbenamt, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Salarymult, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Salarymult, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Salarymult, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Bencap, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Bencap, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Bencap, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
X
</div>
</div>
}
</div>
Here's my controller action where I'm getting the proper responseId and assigning it to the form values:
public ActionResult CreateBasicLifeResponse(ResponseBasicLife model)
{
for (var i = 1; i < model.basiclives.Count; i++)
{
string currentUserId = User.Identity.GetUserId();
Response targetresponse = db.response.FirstOrDefault(x => x.Userid == currentUserId);
int responseid = targetresponse.Id;
model.basiclives[i].ResponseId = responseid;
db.basiclife.Add(model.basiclives[i]);
db.SaveChanges();
}
ResponseBasicLife basicliferesponse = new ResponseBasicLife
{
basiclives = new List<Basiclife>
{
new Basiclife { }
}
};
return View(basicliferesponse);
}
The only thing that's being written to the database is the ResponseID. How do I get the rest of the values to write to it?
This is a unique case where EditorFor could help. Essentially an object will have its editor template which is kind of like a partial view but specific to editing forms.
Secondly, the being form you are specifying is expecting the model of the view that you specified - in your case the viewWrapper. If for instance you specified a List<BasicLife>, then that is what the postBack shall be expecting, and not the BasicLife object. Below is how your postback would look like.
[HttpPost]
public ActionResult CreateBasicLifeResponse(List<BasicLife> model){
//your code goes here
}
From your view though, it looks clear that Model contains more than just a list. That is what shall be expected from the callback.

Passing ViewModel List Data to controller

I have a ViewModel as such:
public class AddNewsModel
{
public List<CategoriesModel> Category { get; set; }
public NewsModel NewsModel { get; set; }
}
where Category contains:
public class CategoriesModel
{
public string Name { get; set; }
public int ID { get; set; }
}
and NewsModel contains:
public class NewsModel
{
public int ID { get; set; }
public string Category { get; set; }
public String Headline { get; set; }
public string Source { get; set; }
public DateTime Publish_Date { get; set; }
public string Text { get; set; }
public string Summary { get; set; }
public string TimeAgo { get; set; }
public string ImageURL { get; set; }
public string CategoryID { get; set; }
}
I have a View where I take form input for News using NewsModel, but I want to display possible categories as a dropdown list or select Tag from the CategoriesModel.
This is My View:
<h2>Add a News Article</h2>
#if (TempData["Success"] != null)
{
<p class="alert alert-success" id="successMessage">#TempData["Success"]</p>
}
#using (Html.BeginForm("AddNews", "Admin", FormMethod.Post))
{
#Html.AntiForgeryToken()
<div class="form-horizontal" id="addNews">
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.Label("News ID", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-1">
#Html.EditorFor(model => model.NewsModel.ID, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.NewsModel.ID, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.NewsModel.Category, htmlAttributes: new { #class = "control-label col-md-2" })
#Html.DropDownListFor(model => model.Category, new SelectList(Model.Category), "Select Category")
#*<div class="col-md-2">
<select form="addNews" id="NewsModel_Category" name="NewsModel.Category">
#foreach (var item in Model.Category)
{
<option value="#item.Name">#item.Name</option>
}
</select>
</div>*#
</div>
<div class="form-group">
#Html.LabelFor(model => model.NewsModel.Headline, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-6">
#Html.EditorFor(model => model.NewsModel.Headline, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.NewsModel.Headline, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.NewsModel.Source, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-6">
#Html.EditorFor(model => model.NewsModel.Source, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.NewsModel.Source, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.Label("Publish Date", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-4">
#Html.EditorFor(model => model.NewsModel.Publish_Date, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.NewsModel.Publish_Date, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.NewsModel.Text, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-6">
#Html.TextAreaFor(model => model.NewsModel.Text, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.NewsModel.Text, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.NewsModel.Summary, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-6">
#Html.TextAreaFor(model => model.NewsModel.Summary, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.NewsModel.Summary, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.NewsModel.ImageURL, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-6">
#Html.EditorFor(model => model.NewsModel.ImageURL, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.NewsModel.ImageURL, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
}
This line of code:
#Html.DropDownListFor(model => model.Category, new SelectList(Model.Category), "Select Category")
gets all the categories, but only displays them as the model I have imported int the view, viz. "MVCApplication.Models.AddNewsModel", instead of a category like "World" or "Tech"
This code that I have commented, returns null when i try to get the data in my HTTPPost controller action using formcollection. I have tried using the ID that i have provided as: string x= formCollection["category"];
<div class="col-md-2">
<select form="addNews" id="category" name="category">
#foreach (var item in Model.Category)
{
<option value="#item.Name">#item.Name</option>
}
</select>
</div>
How can I show the categories in my View, as well as get the value in the controller?
Any help would be appreciated.
Edit:
I am populating The Categories list in my controller action as:
public ActionResult AddNews()
{
AddNewsModel AddNewsModel = new AddNewsModel();
AddNewsModel.Categories = new NewsArticles().GetCategories();
return View(AddNewsModel);
}
Changing my model to an Ienumerable instead of list causes errors in my controller I cannot seem to solve.
your model should be like this:
public class AddNewsModel
{
public IEnumerable<SelectListItem> CategorySelectList { get; set; }
public int CategoryId {get; set;}
public NewsModel NewsModel { get; set; }
}
and in the view :
#Html.DropDownListFor(model => model.CategoryId, Model.CategorySelectList, "Select Category")
for more details -> link
You should have both Cateogory and List with all categories in the model
public class AddNewsModel
{
public int Category { get; set; }
public IEnumerable<SelectListItem> Categories { get; set;}
public NewsModel NewsModel { get; set; }
}
View
update your dropdownlist with list.
<h2>Add a News Article</h2>
#if (TempData["Success"] != null)
{
<p class="alert alert-success" id="successMessage">#TempData["Success"]</p>
}
#using (Html.BeginForm("AddNews", "Admin", FormMethod.Post))
{
#Html.AntiForgeryToken()
<div class="form-horizontal" id="addNews">
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.Label("News ID", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-1">
#Html.EditorFor(model => model.NewsModel.ID, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.NewsModel.ID, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.NewsModel.Category, htmlAttributes: new { #class = "control-label col-md-2" })
#Html.DropDownListFor(model => model.Category, Model.Categories, "Select Category")
#*<div class="col-md-2">
<select form="addNews" id="NewsModel_Category" name="NewsModel.Category">
#foreach (var item in Model.Category)
{
<option value="#item.Name">#item.Name</option>
}
</select>
</div>*#
</div>
<div class="form-group">
#Html.LabelFor(model => model.NewsModel.Headline, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-6">
#Html.EditorFor(model => model.NewsModel.Headline, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.NewsModel.Headline, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.NewsModel.Source, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-6">
#Html.EditorFor(model => model.NewsModel.Source, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.NewsModel.Source, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.Label("Publish Date", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-4">
#Html.EditorFor(model => model.NewsModel.Publish_Date, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.NewsModel.Publish_Date, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.NewsModel.Text, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-6">
#Html.TextAreaFor(model => model.NewsModel.Text, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.NewsModel.Text, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.NewsModel.Summary, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-6">
#Html.TextAreaFor(model => model.NewsModel.Summary, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.NewsModel.Summary, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.NewsModel.ImageURL, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-6">
#Html.EditorFor(model => model.NewsModel.ImageURL, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.NewsModel.ImageURL, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
}

MVC 5 Code First Editing

Hey guys i am coding in MVC 5 code first now i have this table below when i want to edit a Cell number or an email and my changes are saved on the database my Picture got deleted i do not know why because i did not change it. every time i Edit other information the Picture got delete when i save my changes
[Key]
public int Member_Id { get; set; }
[Required]
[StringLength(20, MinimumLength = 3, ErrorMessage = "Please enter minimum of 3 characters")]
[RegularExpression(#"^[a-zA-Z\s?]+$", ErrorMessage = "Pease enter valid name!")]
[Display(Name = "First Name")]
public string Name { get; set; }
[Required]
[RegularExpression(#"^[a-zA-Z\s?]+$", ErrorMessage = "Pease enter valid Surname!")]
[StringLength(20, MinimumLength = 3, ErrorMessage = "Please enter minimum of 3 characters")]
[Display(Name = "Surname")]
public string Surname { get; set; }
[Required]
[RegularExpression(#"^(\d{10})$", ErrorMessage = "Cellphone number must be 10 digits!")]
[Display(Name = "Cell Number")]
public string Cell_Number { get; set; }
[Required]
[RegularExpression(#"^(\d{13})$", ErrorMessage = "id must be 13 digits!")]
[Display(Name = "ID Number")]
public string ID_Number { get; set; }
[Required]
[RegularExpression(".+\\#.+\\..+", ErrorMessage = "Please enter a valid email address")]
[Display(Name = "Email Address")]
public string Email { get; set; }
[Required]
[Display(Name = "Physical Address")]
public string Address { get; set; }
[Display(Name = "Owner")]
public bool Owner { get; set; }
[Display(Name = "Driver")]
public bool Driver { get; set; }
[Display(Name = "Rank Manager")]
public bool Rank_Manager { get; set; }
[Display(Name = "Profile Picture")]
public byte[] Picture { get; set; }
public string alter_Text { get; set; }
public string ImageMimeType { get; set; }
public virtual ICollection<Taxi> Taxi { get; set; }
and this is my controller
public ActionResult EditPick(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Member member = db.Member.Find(id);
if (member == null)
{
return HttpNotFound();
}
return View(member);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult EditPick(/*[Bind(Include = "Member_Id,Name,Surname,Cell_Number,ID_Number,Email,Address,Owner,Driver,Rank_Manager,Picture,alter_Text,ImageMimeType")]*/ Member member,HttpPostedFileBase image)
{
try
{
var picturee = new Member();
if (image != null)
{
if (image.ContentLength > 2 * 1024 * 1024)
{
ModelState.AddModelError("CustomError", "The File size be not more than 2 MB");
return View();
}
if (!(image.ContentType == "image/jpeg" || image.ContentType == "image/gif"))
{
ModelState.AddModelError("CustomError", "The File Allowed : jpeg and gif");
return View();
}
if (image != null)
{
member.ImageMimeType = image.ContentType;
member.Picture = new byte[image.ContentLength];
image.InputStream.Read(member.Picture, 0, image.ContentLength);
}
}
picturee.Member_Id = member.Member_Id;
picturee.Name = member.Name;
picturee.Surname = member.Surname;
picturee.Cell_Number = member.Cell_Number;
picturee.ID_Number = member.ID_Number;
picturee.Email = member.Email;
picturee.Address = member.Address;
picturee.Owner = member.Owner;
picturee.Driver = member.Driver;
picturee.Rank_Manager = member.Rank_Manager;
picturee.Picture = member.Picture;
picturee.ImageMimeType = member.ImageMimeType;
picturee.alter_Text = member.alter_Text;
db.Entry(picturee).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
catch (DataException)
{
ModelState.AddModelError("", "Sorry can not update contact Administrator");
}
return View(member);
}
This is my View when posting
#using (Html.BeginForm(null, null, FormMethod.Post, new { enctype = "multipart/form-data" }))
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Member</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
#Html.HiddenFor(model => model.Member_Id)
<div class="form-group">
#Html.LabelFor(model => model.Name, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Name, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Name, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Surname, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Surname, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Surname, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Cell_Number, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Cell_Number, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Cell_Number, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.ID_Number, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.ID_Number, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.ID_Number, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Email, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Email, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Email, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Address, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Address, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Address, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Owner, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
<div class="checkbox">
#Html.EditorFor(model => model.Owner)
#Html.ValidationMessageFor(model => model.Owner, "", new { #class = "text-danger" })
</div>
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Driver, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
<div class="checkbox">
#Html.EditorFor(model => model.Driver)
#Html.ValidationMessageFor(model => model.Driver, "", new { #class = "text-danger" })
</div>
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Rank_Manager, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
<div class="checkbox">
#Html.EditorFor(model => model.Rank_Manager)
#Html.ValidationMessageFor(model => model.Rank_Manager, "", new { #class = "text-danger" })
</div>
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Picture, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#{
if (Model.Picture != null)
{
string imageBase64 = Convert.ToBase64String(Model.Picture);
string imageSrc = string.Format("data:image/gif;base64,{0}", imageBase64);
<img src="#imageSrc" width="100" height="100" />
}
}
#Html.ValidationMessageFor(model => model.Picture, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.alter_Text, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.alter_Text, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.alter_Text, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.ImageMimeType, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.ImageMimeType, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.ImageMimeType, "", new { #class = "text-danger" })
</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>
As said in comments, you need to add a Input=File Name=Image in your view to post back the file with the changes to your profile picture, but the most important thing to do, is to read back the member info from you database and not build a new one instance of a member.
Actually your new member has no info on the previous image if the view don't post back a file and when you save you loose the image bytes.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult EditPick(Member member,HttpPostedFileBase image)
{
try
{
var picturee = new context.Member.Find(member.Member_Id);
if(picturee != null)
{
.....
}
// Now you can start updating the other fields and then save.
// This is not needed -> picturee.Member_Id = member.Member_Id;
picturee.Name = member.Name;
picturee.Surname = member.Surname;
....
In this way you reload the image bytes in case the View don't post back a file to read
In the view you need to add the appriate code to post back the profile image if the user want it updated.
<div class="form-group">
#Html.LabelFor(model => model.Picture, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
<input name="Image" type="file" />
</div>
#{
if (Model.Picture != null)
{
string imageBase64 = Convert.ToBase64String(Model.Picture);
string imageSrc = string.Format("data:image/gif;base64,{0}", imageBase64);
<img src="#imageSrc" width="100" height="100" />
}
}
#Html.ValidationMessageFor(model => model.Picture, "", new { #class = "text-danger" })
</div>

Saving Many to Many in MVC asp.net

i read a lot about MVC. But until now there is no clear answer how to handle many to many relation cause many of these tutorial result have the same bug.
I am using Database first approach, my application should add Users and while adding users I should have a list from the roles and i could add these roles to this user or the opposite i could have roles with list of user and edit and as we know when I add the data base with breaking table to ado.net so the relation will be many to many.
I have successfully add list of the roles but when i press save i got the exception of null reference.
And this is my code :
First the custom view :
namespace UserMangment.ViewModel
{
public class RolesViewMode
{
public tab_OnlineUsers OnlineUsers { get; set; }
public IEnumerable<SelectListItem> AllRolesnames { get; set; }
private List<string> _selectedRolesname;
public List<string> SelectedRoleTags
{
get
{
if (_selectedRolesname == null)
{
_selectedRolesname = OnlineUsers.tab_OnlineRoles.Select(m => m.Id).ToList();
}
return _selectedRolesname;
}
set { _selectedRolesname = value; }
}
}
}
Then the controller :
namespace ELVIRA_UserMangment.Controllers
{
public class OnlineUsersController : Controller
{
private Entities db = new Entities();
// GET: OnlineUsers
public ActionResult Index()
{
return View(db.tab_OnlineUsers.ToList());
}
// GET: OnlineUsers/Details/5
public ActionResult Details(string id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
tab_OnlineUsers tab_OnlineUsers = db.tab_OnlineUsers.Find(id);
if (tab_OnlineUsers == null)
{
return HttpNotFound();
}
return View(tab_OnlineUsers);
}
// GET: OnlineUsers/Create
public ActionResult Create()
{
var RolesViewmode = new RolesViewMode
{
OnlineUsers = db.tab_OnlineUsers.Create(),
};
if (RolesViewmode.OnlineUsers == null)
return HttpNotFound();
var allrolles = db.tab_OnlineRoles.ToList();
RolesViewmode.AllRolesnames = allrolles.Select(o => new SelectListItem
{
Text = o.Name,
Value = o.Id.ToString()
});
return View(RolesViewmode);
}
// POST: OnlineUsers/Create
// Aktivieren Sie zum Schutz vor übermäßigem Senden von Angriffen die spezifischen Eigenschaften, mit denen eine Bindung erfolgen soll. Weitere Informationen
// finden Sie unter http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "Id,Email,EmailConfirmed,PasswordHash,SecurityStamp,PhoneNumber,PhoneNumberConfirmed,TwoFactorEnabled,LockoutEndDateUtc,LockoutEnabled,AccessFailedCount,UserName")] RolesViewMode tab_OnlineUsers)
{
if (ModelState.IsValid)
{
try
{
db.tab_OnlineUsers.Add(tab_OnlineUsers.OnlineUsers);
db.SaveChanges();
return RedirectToAction("Index");
}
catch(DbEntityValidationException e)
{
Console.WriteLine(e);
}
}
return View(tab_OnlineUsers);
}
// GET: OnlineUsers/Edit/5
public ActionResult Edit(string id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
var RolesViewmode = new RolesViewMode
{
OnlineUsers = db.tab_OnlineUsers.Include(i => i.tab_OnlineRoles).First(i => i.Id == id),
};
if (RolesViewmode.OnlineUsers == null)
return HttpNotFound();
var allrolles = db.tab_OnlineRoles.ToList();
RolesViewmode.AllRolesnames = allrolles.Select(o => new SelectListItem
{
Text = o.Name,
Value = o.Id.ToString()
});
tab_OnlineUsers tab_OnlineUsers = db.tab_OnlineUsers.Find(id);
if (tab_OnlineUsers == null)
{
return HttpNotFound();
}
return View(RolesViewmode);
}
// POST: OnlineUsers/Edit/5
// Aktivieren Sie zum Schutz vor übermäßigem Senden von Angriffen die spezifischen Eigenschaften, mit denen eine Bindung erfolgen soll. Weitere Informationen
// finden Sie unter http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "Id,Email,EmailConfirmed,PasswordHash,SecurityStamp,PhoneNumber,PhoneNumberConfirmed,TwoFactorEnabled,LockoutEndDateUtc,LockoutEnabled,AccessFailedCount,UserName")] tab_OnlineUsers tab_OnlineUsers)
{
if (ModelState.IsValid)
{
db.Entry(tab_OnlineUsers).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(tab_OnlineUsers);
}
Then finally the create view:
#model UserMangment.ViewModel.RolesViewMode
#{
ViewBag.Title = "Create";
}
<h2>Create</h2>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>tab_OnlineUsers</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.OnlineUsers.Id, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model =>model.OnlineUsers.Id, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model =>model.OnlineUsers.Id, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model =>model.OnlineUsers.Email, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model =>model.OnlineUsers.Email, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model =>model.OnlineUsers.Email, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model =>model.OnlineUsers.EmailConfirmed, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
<div class="checkbox">
#Html.EditorFor(model =>model.OnlineUsers.EmailConfirmed)
#Html.ValidationMessageFor(model =>model.OnlineUsers.EmailConfirmed, "", new { #class = "text-danger" })
</div>
</div>
</div>
<div class="form-group">
#Html.LabelFor(model =>model.OnlineUsers.PasswordHash, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model =>model.OnlineUsers.PasswordHash, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model =>model.OnlineUsers.PasswordHash, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model =>model.OnlineUsers.SecurityStamp, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model =>model.OnlineUsers.SecurityStamp, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model =>model.OnlineUsers.SecurityStamp, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model =>model.OnlineUsers.PhoneNumber, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model =>model.OnlineUsers.PhoneNumber, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model =>model.OnlineUsers.PhoneNumber, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model =>model.OnlineUsers.PhoneNumberConfirmed, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
<div class="checkbox">
#Html.EditorFor(model =>model.OnlineUsers.PhoneNumberConfirmed)
#Html.ValidationMessageFor(model =>model.OnlineUsers.PhoneNumberConfirmed, "", new { #class = "text-danger" })
</div>
</div>
</div>
<div class="form-group">
#Html.LabelFor(model =>model.OnlineUsers.TwoFactorEnabled, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
<div class="checkbox">
#Html.EditorFor(model =>model.OnlineUsers.TwoFactorEnabled)
#Html.ValidationMessageFor(model =>model.OnlineUsers.TwoFactorEnabled, "", new { #class = "text-danger" })
</div>
</div>
</div>
<div class="form-group">
#Html.LabelFor(model =>model.OnlineUsers.LockoutEndDateUtc, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model =>model.OnlineUsers.LockoutEndDateUtc, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model =>model.OnlineUsers.LockoutEndDateUtc, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model =>model.OnlineUsers.LockoutEnabled, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
<div class="checkbox">
#Html.EditorFor(model =>model.OnlineUsers.LockoutEnabled)
#Html.ValidationMessageFor(model =>model.OnlineUsers.LockoutEnabled, "", new { #class = "text-danger" })
</div>
</div>
</div>
<div class="form-group">
#Html.LabelFor(model =>model.OnlineUsers.AccessFailedCount, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model =>model.OnlineUsers.AccessFailedCount, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model =>model.OnlineUsers.AccessFailedCount, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model =>model.OnlineUsers.UserName, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model =>model.OnlineUsers.UserName, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model =>model.OnlineUsers.UserName, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.AllRolesnames, "Roles Name", new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.ListBoxFor(m => m.SelectedRoleTags, Model.AllRolesnames)
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
}
So this code Success to bring the list,however there is an error to save this information into my database.
Let me just explore to you one technique to over come many to many relation issue.
When ever you face many to many relation in database you should make a lookup table for both tables in database Like:
If you have tables for roles and users (In case more then one roles assign to user) so you should make a lookup table for this work where you save RoleId and UserId (Id,RoleId,UserId etc whatever fields you want to add)..
And whenever role is assign to user you should make a entry in that table.
There may be more possible solution for that but this what I am doing whenever I face many to many relation ship issue..
Thanks,
Hopefully this will help ...

Resources