Update List from other class - c#

I have a MVC Application with Index and Detail view. Index show _peticiones list items. And I want to update this list from Detail view.
Detail View
#using (Html.BeginForm())
{
<div class="form-group">
<label for="id">Id:</label>
#Html.TextBoxFor(m => m.Id, new { #id = "id", #class = "form-control", #readonly = "readonly" })
</div>
<div class="form-group">
<label for="nombre">Nombre:</label>
#Html.TextBoxFor(m => m.Nombre, new { #nombre = "nombre", #class = "form-control"})
</div>
<div class="form-group">
<label for="desc">Descripcion:</label>
#Html.TextBoxFor(m => m.Desc, new { #dec = "desc", #class = "form-control"})
</div>
<div class="form-group">
<label for="fecha">Fecha:</label>
#Html.TextBoxFor(m => m.Fecha, new { #fecha = "fecha", #class = "form-control"})
</div>
<div class="form-group">
<label for="activo">Activo:</label>
#Html.TextBoxFor(m => m.Activo, new { #activo= "activo", #class = "form-control" })
</div>
<div class="container-fluid">
<div class="col-md-12 text-right">
<input type="submit" value="Guardar" class="btn btn-primary" />
</div>
</div>
}
Controller (Update method has "id" as parameter, i can't use object like a parameter)
public ActionResult Detail(Peticion peticion)
{
if (ModelState.IsValid)
{
var id = peticion.Id;
_peticionService.Update(id);
return RedirectToAction("Index");
}
return View();
}
Class PeticionService
public bool Update(int id)
{
if (id > 0)
{
var peticionOld = _peticiones.FirstOrDefault(u => u.Id == id);
if (peticionOld != null)
{
//How to update item list??
return true;
}
}
return false;
}
How can I update list from "PeticionService" class with just id?

I would approach your problem like the below.
Create a view model for your view.
public class PeticoneViewModel
{
public Peticione CurrentPeticione { get; set; }
}
Then have a service that handles the retrieval and updates to the list source.
public class PeticoneService
{
public Peticione GetPeticioneByID(int id)
{
//Put your implementation here.
return new Peticione();
}
public bool SavePeticioneByID(int id, string newValue)
{
//Put your implementation here.
return true;
}
}
Then create a controller to return the Detail view and handle the update
public class PeticioneController : Controller
{
public ActionResult Detail(int peticonID)
{
var peticoneService = new PeticoneService();
var peticoneViewModel = new PeticoneViewModel();
peticoneViewModel.CurrentPeticione = peticoneService.GetPeticioneByID(peticonID);
return View("Detail",peticoneViewModel);
}
public bool UpdatePeticone(int id, string newValue)
{
if (id > 0)
{
var peticoneService = new PeticoneService();
return peticoneService.SavePeticioneByID(id, newValue);
}
return false;
}
}
Also in an ideal world your service should be injected into the controller so the controller isn't responsible for the service instantiation. But that's another issue.
Hope the above helps.

Related

How to pass List box selected Items from view to the controller model?

I have a list-box with options. User can select all or select any one, so all i need is to bind the selected to the model on the controller.Now it comes as empty even though i have selected some.
I have populated the data to the List-box already. LoadAllControls method is in the index controller.
Loading data to List-box. This works 100%
public void LoadAllControls(myModel model)
{
try
{
string jsonReq = null;
string jsonResp = null;
//API call here
jsonResp = JsonWrapper.JsonGET(jsonReq);
List<Structs> listOrderTypes = DeserialiseFromJson<List<Structs>>.Deserialise(jsonResp);
List<SelectListItem> listO = listOrderTypes.Select(item => new SelectListItem
{
Value = item.orderType.ToString(),
Text = item.orderTypeName,
Selected = "-1" == (item.orderTypeCode.ToString()) ? true : false
}).ToList();
model.orderTypes = new List<SelectListItem>(listO);
}
catch(Exception exx)
{
throw exx;
}
}
View
#using (Ajax.BeginForm("Search", "myController", new AjaxOptions { HttpMethod = "Post" }))
{
<div class="form-group">
<label class="control-label col-sm-2" for="txtfrom">Order Type:</label>
<div class="col-md-4">
#Html.ListBoxFor(m => m.orderTypesIds, Model.orderTypes, new { #class = "form-control listbox", id = "orderTypeIdList", #multiple = "multiselect" })
</div>
</div>
<div class="form-group">
<div class="col-sm-10 col-sm-offset-2">
<button class="btn btn-primary " id="btnSearch" name="SearchButton" type="submit">
Search
</button>
</div>
</div>
}
Controller
public ActionResult Search(myModel model)
{
//Selected options comes as null to the model
//Some logic here
}
My Model
public class myModel
{
public List<SelectListItem> orderTypes { get; set; }
public int[] orderTypesIds { get; set; }
}

MVC how to update related navigation property

EDIT reformed my question based on #Stephen Muecke answer ..
it took me months trying to resolve such problem, but failed to.
my entities are:
public partial class Book
{
public int bookID { get; set; }
public string name { get; set; }
public string chapter { get; set; }
public virtual ICollection<Root> roots { get; set; }
}
.
public class Root
{
public int rootID { get; set; }
public string rooting { get; set; }
public virtual ICollection<Book> Book{ get; set; }
}
BooksController:
public class BooksController : Controller
{
private Context db = new Context();
// GET: Books
public ActionResult Index()
{
var boo = db.books.Include(x => x.roots).ToList();
List<RootyVM> model = new List<RootyVM>();
return View(boo);
}
....
....
// GET: Books/Create
public ActionResult Create()
{
return View();
}
// POST: Books/Create
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(IEnumerable<RootyVM> rootings, Book book)
{
if (ModelState.IsValid)
{
db.books.Add(book);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(book);
}
my view model RootyVM:
public class RootyVM
{
public int? rootID { get; set; }
[Required(ErrorMessage = "Please enter the name of the root!!")]
public string rooting { get; set; }
}
and my partial view _Rooting.cshtml
#model project.ViewModels.RootyVM
<div class="rooting">
#using (Html.BeginCollectionItem("rooting"))
{
#Html.HiddenFor(m => m.rootID, new { #class = "rootID" })
#Html.LabelFor(m => m.rooting)
#Html.TextBoxFor(m => m.rooting)
<button type="button" class="delete">Delete</button>
}
</div>
and my Razor view (Create.cshtml) as follows:
#model project.Models.Book
#{
ViewBag.Title = "Create";
}
<h2>Create</h2>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Book</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<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.chapter, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.chapter, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.chapter, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#using (Html.BeginForm())
{
<div id="rootings">
foreach(var rooting in Model)
{
#Html.Partial("_Rooting", rooting)
}
</div>
<button id="add" type="button">Add</button>
<input type="submit" value="Save" />
}
</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>
<script type="text/javascript">
var url = '#Url.Action("Rooting")';
var form = $('form');
var rootings = $('#rootings');
$('#add').click(function() {
$.get(url, function(response) {
rootings.append(response);
// Reparse the validator for client side validation
form.data('validator', null);
$.validator.unobtrusive.parse(form);
});
});
$('.delete').click(function() {
var container = $(this).closest('.rooting');
var id = container.find('.id').val();
if (id) {
// make ajax post to delete item
$.post(yourDeleteUrl, { id: id }, function(result) {
container.remove();
}.fail(function (result) {
// Oops, something went wrong (display error message?)
}
} else {
// It never existed, so just remove the container
container.remove();
}
});
</script>
}
HOWEVER, there is a mistake where i cannot find. Will appreciate your patience and help
ORIGINAL MAIN REQUESTS
however, I'm struggling in Create and Edit method. What I need to do is that:
Create a new book record and assign a root or more in the same view.
using dropdownlist is preferable.
if root doesn't exist, i want to add/create it on the fly, I mean immediately in the same create view.
I would appreciate if the Create view for relationship property i.e. Root is based on java where token are used (Select2).
I hope I made it clear for you to help me.

MVC auto validation

I am making my MVC application. I created a view, in which a user picks data from dropdown list. The view is like this:
#Scripts.Render("~/bundles/jquery")
#Scripts.Render("~/bundles/bootstrap")
#using ClassDeclarationsThsesis.Classes
#using Microsoft.Ajax.Utilities
#model ClassDeclarationsThsesis.Models.ClassesViewModel
#{ ViewBag.Title = "Classes";
}
<h2>Classes</h2>
#foreach (var user in Model.users)
{
if (user.email.Replace(" ", String.Empty) == HttpContext.Current.User.Identity.Name)
{
if (user.user_type.Replace(" ", String.Empty) == 3.ToString() || user.user_type.Replace(" ", String.Empty) == 2.ToString())
{
using (Html.BeginForm("Classes", "Account", FormMethod.Post, new { #class = "form-horizontal", role = "form" }))
{
#Html.AntiForgeryToken()
<h4>Generate summary views</h4>
<hr />
#Html.ValidationSummary("", new { #class = "text-danger" })
<div class="form-group">
#{
List<SelectListItem> listItems1 = new List<SelectListItem>();
}
#foreach (var subject in Model.subject)
{
listItems1.Add(new SelectListItem
{
Text = subject.name,
Value = subject.name,
});
}
#Html.LabelFor(m => m.subject_name, new { #class = "col-md-2 control-label" })
<div class="col-md-10">
#Html.DropDownListFor(m => m.subject_name, listItems1, new { #class = "form-control" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" class="btn btn-default" value="Submit" />
</div>
</div>
}
}
if (user.user_type.Replace(" ", String.Empty) == 1.ToString())
{
<p>You do not have enough permissions to enter this page. Contact the administrator.</p>
}
}
}
The controller is:
public ActionResult Classes()
{
ClassDeclarationsDBEntities1 entities = new ClassDeclarationsDBEntities1();
var model = new ClassesViewModel();
model.subject = entities.Subjects.ToList();
model.users = entities.Users.ToList();
if (ModelState.IsValid)
{
return RedirectToAction("ClassesPickGroup", "Account", new { subject_name=model.subject_name});
}
return View(model);
}
And the model:
public class ClassesViewModel
{
public List<Subject> subject { set; get; }
public List<User> users { get; set; }
[Required]
[Display(Name = "Subject")]
public string subject_name { get; set; }
}
But since the view only contains a single dropdown list, it is always Valid and redirects to different view straight away. How do I make the application wait for user choice in dropdown list and then submit the answer?
There is no problem in your view, but the problem that you create new object every time user submit and check for validation
public ActionResult Classes(ClassesViewModel model)
{
ClassDeclarationsDBEntities1 entities = new ClassDeclarationsDBEntities1();
if (ModelState.IsValid)
{
return RedirectToAction("ClassesPickGroup", "Account", new { subject_name=model.subject_name});
}
else {
model.subject = entities.Subjects.ToList();
model.users = entities.Users.ToList();
return View(model);
}
}

How to create drop down list in Create.cshtml

How to create drop down list in Create.cshtml, where the list is made of data from DB and if there is no such kind of data you want to choose you can enter new value and it saves in DB.
I tried to query from DB to a list and used ViewBag.DropDownList (it worked in Index.cshtml, but not in Create.cshtml, because I was getting error: There is no ViewData item of type 'IEnumerable' that has the key "MyDropDownList")
Create.cshtml:
#using LicenseManager.Models
#model LicenseManager.Models.CompanyNames
#{
ViewBag.Title = "Create";
}
<h2>Create</h2>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>CompanyNames</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<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.DropDownList("CompanyNames", (SelectList)ViewBag.DropDownValues)
</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>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval") }
and controller CompanyNames.cs:
public class CompanyNamesController : Controller
{
private ApplicationDbContext db = new ApplicationDbContext();
// GET: CompanyNames
public ActionResult Index()
{
ApplicationDbContext db = new ApplicationDbContext();
var querys = from c in db.CompanyNames
select c.Name;
ViewBag.DropDownValues = new SelectList(querys);
return View(db.CompanyNames.ToList());
}
}
Can someone help me with this? I just need some kind of direction where to go, to do. Sorry for the code....
model created :
public class CustomerModel
{
public List<SelectListItem> ListAdCode { get; set; }
}
Create a function to bind a list :
public static List<SelectListItem> AdCodeList()
{
List<SelectListItem> list = new List<SelectListItem>();
list.Add(new SelectListItem { Text = "--Select--", Value = null, Selected = true });
using (CrmKolmEntities entities = new CrmKolmEntities())
{
var allActiveCAdCodes = entities.AdCodes.Where(x => x.IsDeleted == false).ToList();
if (allActiveCAdCodes.Count() > 0)
{
foreach (var adCode in allActiveCAdCodes)
{
list.Add(new SelectListItem { Text = adCode.AdCodeName, Value = adCode.AdCodeId.ToString() });
}
}
}
return list;
}
On Controller :
public ActionResult ManipulateCustomer(int id, int? idOrder)
{
CustomerModel model = new CustomerModel();
model.ListAdCode = AdCodeList();
if (model.ListPriceList == null)
{
model.ListPriceList = CommonFunctions.PriceListActive(null);
}
return View(model);
}
On View:
#Html.DropDownListFor(r => r.AdCodeId, new SelectList(Model.ListAdCode, "value", "text", "selectedValue"), new { #class = "input", #style = "width:450px" })
I think you need Html.DropDownList instead of ViewBag.DropDownList. The former is from the HtmlHelper class and I think it's what you need. You can read more about it here.

Model Binding Postback

I have 2 methods like this
public ViewResult Detail(int Id)
{
if (Id != null)
{
Context context = new Context();
Poll PollDetail = context.Polls.FirstOrDefault(x => x.Id == Id);
PollDetail.Answers = new List<Answer>();
Context Context = new Context();
PollDetail.Answers = Context.Answers.Where(x => x.PollId == PollDetail.Id).ToList();
return View("../Home/Index", PollDetail);
}
RedirectToAction("Index", "Home");
}
[HttpPost]
public ActionResult PollVote(Poll CurrentPoll)
{
Context Context = new Context();
foreach (Answer item in CurrentPoll.Answers)
{
item.VoteCount = item.VoteCount + 1;
}
return View();
}
There cshtml. so there is no problem to this section.
<div class="container">
#Html.Partial("Header")
#if (Model == null)
{
#Html.Partial("CreatePoll")
}
else
{
using (#Html.BeginForm("PollVote", "Poll", FormMethod.Post, new { id = "PollVoteForm" }))
{
<div class="row-fluid">
<div class="span12 pageHeader">
<h2>SORU:</h2>
#Html.LabelFor(m => m.Question, Model.Question, new { #class = "question-input", #id = "question" })
</div>
</div>
<div id="answers" class="row-fluid">
#foreach (Answer answer in Model.Answers)
{
<p class="external">
#Html.RadioButtonFor(m => answer.Content, answer.Content, new { #name = "rb", #class = "answer-radio", #id = "answer-" + answer.Counter, #checked = "false" })
#Html.Label(answer.Content, new { #for = "answer-" + answer.Counter })
#Html.HiddenFor(m => answer.Content)
</p>
}
</div>
<div class="row-fluid">
<div class="span6"></div>
<div class="span5">
<input type="submit" value="Oyla" class="btnPS" />
</div>
</div>
}
}
<div class="footer"></div>
</div>
Poll model perfectly binded. But i cant back any data. when i submit form in index.cshtml. CurrentPoll model comes null. How can i fix it ?
Asp.Net MVC require propertioes on your model in order for the model binding. Hence check your model and ensure all members are exposed as properties.
Eg: You change your model to something like below.
public class Poll
{
public Answer Answers { get; set; }
}

Categories

Resources