Return result from another apicontroller - c#

Hi I'm trying to call the Get method in my CategoryController from my WareController. How would I do that.
I've tried this in my WareController
// GET: api/Ware?category=5
public List<WareDTO> GetByCategroy(int id)
{
BLLServiceGateway<List<WareDTO>> gate = new BLLServiceGateway<List<WareDTO>>();
var item = gate.Get(path + "?category=" + id);
if (item == null)
{
throw new HttpResponseException(HttpStatusCode.NotFound);
}
return item;
}
public IHttpActionResult ViewItems(int id)
{
var model = new WareModel()
{
wares = GetByCategroy(id),
currentCategory = Redirect("api/category/" + id) /// This is were I want to get the category object
};
}
return Ok(model);
and my CategoryController looks like this
// GET: api/Categories/5
public CategoryDTO Get(int id)
{
BLLServiceGateway<CategoryDTO> gate = new BLLServiceGateway<CategoryDTO>();
var item = gate.Get(path + id);
if (item == null)
{
throw new HttpResponseException(HttpStatusCode.NotFound);
}
return item;
}

API controller are just classes, so you easily can do this:
currentCategory = new CategoryController().Get(id);
But there may me problems if you want to deal with context.

Related

return to view after addModelError

in this project i create cardGroup. in httpGet Method we get some needed info and pass to view to fill dropdown. when httpPost trigger if some field Date has Problem we must return error with addModelError but after return View, all ViewData Clear and Return Exception. how can handle this. just show error in view.
[HttpGet]
[Route("CreateCardGroup")]
public ActionResult CreateCardGroup()
{
var discounts =
UnitOfWork.DiscountPatternRepository.GetNotExpireDiscountPattern();
var discountDtos = discounts?.Select(c => new SelectListItem
{
Text = c.PatternTitle,
Value = c.Id.ToString()
}).ToList();
ViewData["DiscountPatterns"] = discountDtos;
var serials =
UnitOfWork.ChargeCardSerialRepository.GetNotAssignedSerials();
var serialDtos = serials?.Select(c => new SelectListItem
{
Text = c.SerialNumber.ToString(),
Value = c.Id.ToString()
}).ToList();
ViewData["ChargeSerials"] = serialDtos;
ViewData["CardSerialCount"] =
UnitOfWork.GiftCardSerialRepository.GetNotUsedGiftSerials();
return View();
}
[HttpPost]
[Route("CreateCardGroup")]
public ActionResult CreateCardGroup(CardGroupCreateDto dto)
{
if (!ModelState.IsValid)
return View(dto);
if(!UnitOfWork.DiscountPatternRepository
.IsCardGroupDateInRange(dto.DiscountPatternId,
dto.ActiveFromDate, dto.ActiveToDate))
{
ModelState.AddModelError("ActiveFromDate", #"Error In Date.");
return View(dto); <---Problem Here
}
var group = dto.LoadFrom();
var insertedId = UnitOfWork.CardGroupRepository.Add(group);
foreach (var rangeDto in group.CardGroupGiftSerialRanges)
{
for (var i = rangeDto.GiftCardSerialBegin; i <=
rangeDto.GiftCardSerialEnd; i++)
{
var serial =
UnitOfWork.GiftCardSerialRepository.GetBySerial(i);
if (serial != null)
{
serial.CardGroupGiftSerialRangeId = rangeDto.Id;
serial.DiscountPatternId = group.DiscountPatternId;
UnitOfWork.Complete();
}
}
}
return Redirect("/CardGroup");
}
From this article:
ViewData
ViewData is a property of ControllerBase class.
ViewData is used to pass data from controller to corresponding view
Its life lies only during the current request. If redirection occurs, then its value becomes null. It’s required typecasting for getting data and check for null values to avoid error.
So what's happening is once you've done your post back to the server, you're now in a different request, meaning, that you need to repopulate your ViewData items so that their values are populated again, or else they'll be null.
So I'd recommend refactoring your Dropdown population method into a private method on your controller and then call that method in your post when you find a validation error or are just returning by calling return View(dto).
If they're used in other controllers, you can add them to a LookupService or LookupRepository or even a general helpers class that contains your lookup logic (whatever fits into your UnitofWork pattern the best for you), to make them available to those other controllers, instead of having it as a private method as per my example.
So something like this for example:
[HttpGet]
[Route("CreateCardGroup")]
public ActionResult CreateCardGroup()
{
PopulateCreateCardGroupLookups();
return View();
}
[HttpPost]
[Route("CreateCardGroup")]
public ActionResult CreateCardGroup(CardGroupCreateDto dto)
{
if (!ModelState.IsValid)
{
PopulateCreateCardGroupLookups();
return View(dto);
}
if(!UnitOfWork.DiscountPatternRepository
.IsCardGroupDateInRange(dto.DiscountPatternId,
dto.ActiveFromDate, dto.ActiveToDate))
{
ModelState.AddModelError("ActiveFromDate", #"Error In Date.");
PopulateCreateCardGroupLookups();
return View(dto); <---Problem Here
}
var group = dto.LoadFrom();
var insertedId = UnitOfWork.CardGroupRepository.Add(group);
foreach (var rangeDto in group.CardGroupGiftSerialRanges)
{
for (var i = rangeDto.GiftCardSerialBegin; i <=
rangeDto.GiftCardSerialEnd; i++)
{
var serial =
UnitOfWork.GiftCardSerialRepository.GetBySerial(i);
if (serial != null)
{
serial.CardGroupGiftSerialRangeId = rangeDto.Id;
serial.DiscountPatternId = group.DiscountPatternId;
UnitOfWork.Complete();
}
}
}
return Redirect("/CardGroup");
}
private void PopulateCreateCardGroupLookups()
{
var discounts =
UnitOfWork.DiscountPatternRepository.GetNotExpireDiscountPattern();
var discountDtos = discounts?.Select(c => new SelectListItem
{
Text = c.PatternTitle,
Value = c.Id.ToString()
}).ToList();
ViewData["DiscountPatterns"] = discountDtos;
var serials =
UnitOfWork.ChargeCardSerialRepository.GetNotAssignedSerials();
var serialDtos = serials?.Select(c => new SelectListItem
{
Text = c.SerialNumber.ToString(),
Value = c.Id.ToString()
}).ToList();
ViewData["ChargeSerials"] = serialDtos;
ViewData["CardSerialCount"] =
UnitOfWork.GiftCardSerialRepository.GetNotUsedGiftSerials();
}

Xml in Asp.net MVC

What I am trying to do is load an xml file into my mvc application but regardless of how I implement it, it always returns a count of zero, I know the way im doing isnt exactly the best by storing the xml loader in the configuration class which is made by the migrations method but it was working and now it has stopped quoting "only part of the address can be reached" I was wondering if there was a way of fixing this?
Catalog.cs
public class CatalogController : BaseController
{
// GET: Catalog
public ActionResult Index()
{
List<Category> Categories = DbContext.Categories.OrderBy(c => c.Name).ToList();
int NumberofBooks = DbContext.Books.Count();
List<PublicationThumbnail> bookItems = GetBookThumbNails(5);
HomeViewModel homeViewModel = new HomeViewModel(Categories, NumberofBooks, bookItems);
return View(homeViewModel);
}
public ActionResult Search(string c = null, string t = null)
{
string searchMessage = (t == null ? "Publications" : t);
if (c != null)
{
searchMessage += " in " + c;
}
List<PublicationThumbnail> imageThumbNail =
FilterPublications(c, t).Select(p => new PublicationThumbnail(p)).ToList();
SearchViewModel searchViewModel = new SearchViewModel()
{
FilterMessage = searchMessage,
Thumbnails = imageThumbNail,
ResultsCount = imageThumbNail.Count
};
return View(searchViewModel);
}
public ActionResult View(int id)
{
Publication foundPublications = DbContext.Publications.Find(id);
if (foundPublications != null)
{
Account currentUser = null;
if (User.Identity.IsAuthenticated)
{
currentUser = AccountManager.GetCurrentUser(User);
}
return View(new PublicationViewModel(foundPublications, currentUser));
}
return HttpNotFound();
}
[Authorize]
public ActionResult Download(int id)
{
Account account = AccountManager.GetCurrentUser(User);
if (account != null && (account.Subscribed() || account.PurchasedItem(id)))
{
Publication publication = DbContext.Publications.FirstOrDefault(p => p.Id == id);
return View(publication);
}
return HttpNotFound();
}
private List<Publication> FilterPublications(string category, string publicationType)
{
List<Publication> results = new List<Publication>();
if (publicationType != null)
{
if (publicationType.ToLower() == "books")
{
results.AddRange(DbContext.Books);
}
}
else
{
results.AddRange(DbContext.Publications);
}
if (category != null)
{
Category categoryMatch = DbContext.Categories.FirstOrDefault(c => c.Name == category);
if (categoryMatch != null)
{
results = results.Where(p => p.Categories.Contains(categoryMatch)).ToList();
}
}
return results;
}
private List<PublicationThumbnail> GetBookThumbNails(int count)
{
List<Book> books = DbContext.Books.Take(Math.Min(count, DbContext.Books.Count())).ToList();
return books.Select(j => new PublicationThumbnail(j)).ToList();
}
}
Books.xml
<?xml version="1.0" encoding="utf-8" ?>
<Books>
<Book>
<Title>The Rabbit Who Wants to Fall Asleep: A New Way of Getting Children to Sleep</Title>
<Description>The groundbreaking No. 1 bestseller is sure to turn nightly bedtime battles into a loving and special end-of-day ritual. This child-tested, parent-approved story uses an innovative technique that brings a calm end to any child's day.</Description>
<Authors>Carl-Johan Forssén Ehrlin</Authors>
<Chapters>4</Chapters>
<Edition>1</Edition>
<PublicationDate>2016-05-21T10:50:23.5602265-04:00</PublicationDate>
<PublicationFormat>PDF</PublicationFormat>
<FileLocation>App_Data/Publications</FileLocation>
<ISBN>978-3-319-30715-2</ISBN>
<Categories>
<Category>
<Name>Other</Name>
</Category>
</Categories>
<ThumbnailLocation>TheRabbit.jpg</ThumbnailLocation>
<Price>4.00</Price>
</Book>
</Books>
Configuration class
internal sealed class Configuration : DbMigrationsConfiguration<HullUniversityPress.DataAccessLayer.HullPressContext>
{
public Configuration()
{
AutomaticMigrationsEnabled = false;
}
protected override void Seed(HullPressContext context)
{
if (context.Books.Count() == 0)
{
SeedPublicationCategories(context);
SeedBooks(context);
SeedAccounts(context);
SeedSubscriptions(context);
}
}
private XDocument LoadXmlDoc(string fileName)
{
XDocument xmlDoc = XDocument.Load("HullUniversityPress/App_Data/" + fileName);
return xmlDoc;
}
private void SeedBooks(HullPressContext context)
{
XDocument xmlDoc = LoadXmlDoc("Books.xml");
foreach (XElement j in xmlDoc.Root.Elements("Book"))
{
Book newBook = new Book()
{
Title = j.Element("Title").Value,
Description = j.Element("Description").Value,
ISBN = j.Element("ISBN").Value,
FileLocation = j.Element("FileLocation").Value,
ThumbnailLocation = j.Element("ThumbnailLocation").Value,
Chapters = int.Parse(j.Element("Chapters").Value),
Edition = int.Parse(j.Element("Edition").Value),
Langauge = (Language)Enum.Parse(typeof(Language), j.Element("Language").Value),
Authors = j.Element("Authors").Value,
Price = decimal.Parse(j.Element("Price").Value),
PublicationFormat = (PublicationFormat)Enum.Parse(typeof(PublicationFormat), j.Element("PublicationFormat").Value),
PublicationDate = DateTime.Parse(j.Element("PublicationDate").Value)
};
ParseCategories(newBook, context, j.Element("Categories"));
context.Books.Add(newBook);
}
}
private void ParseCategories(Publication publication, HullPressContext context, XElement categoryRoot)
{
publication.Categories = new List<Category>();
foreach (XElement category in categoryRoot.Elements("Category"))
{
string categoryName = category.Element("Name").Value;
Category match = context.Categories.Local.FirstOrDefault(c => c.Name == categoryName);
if (match != null)
{
publication.Categories.Add(match);
match.Publications.Add(publication);
}
else throw new Exception("Unidentified category: " + category.Element("Name").Value + ", Categories: " + context.Categories.Local.Count());
}
}
private void SeedPublicationCategories(HullPressContext context)
{
context.Categories.AddOrUpdate(
new Category("Other")
);
}
private void SeedAccounts(HullPressContext context)
{
context.Accounts.AddOrUpdate(
new Account("Customer#Customer.com", "Hello12345")
);
}
private void SeedSubscriptions(HullPressContext context)
{
Account account = context.Accounts.Local.FirstOrDefault(u => u.Email == "Customer#Customer.com");
Book bookSub = context.Books.Local.FirstOrDefault();
if (account != null && bookSub != null)
{
context.Purchases.Add(new Purchase()
{
Account = account,
Publication = bookSub,
Format = PublicationFormat.PDF
});
}
}
}
Any sort of help / pointed in the right direct would be greatly received.
I'm not sure how that code ever worked,I've re-created the problem on my side and changed this line:
XDocument xmlDoc = XDocument.Load("HullUniversityPress/App_Data/" + fileName);
to this:
XDocument xmlDoc = XDocument.Load(Server.MapPath("~/HullUniversityPress/App_Data/" + fileName));
Now the XDocument is being loaded with the content of Books.xml:

How to make Delete and Edit methods in MVC without DB

I am building a simple MVC CRUD without using a database, but just making methods in a Repository model class.
To make it easier to understand i have 2 model classes. MyNote in which i have some properties and NoteRepository in which i have a list with the properties.
Then I've made a NoteController and i have already made Get and Create methods, but i can't seem to figure out what to write to make an Edit and Delete method? Hope you guys can help.
Here you will see some of the code from my project:
[HttpPost]
public ActionResult Create(MyNote mn)
{
try
{
note.Create(mn);
return RedirectToAction("Index");
}
catch
{
return View();
}
}
this is the create from the Controller.
public static List<MyNote> notes = new List<MyNote>();
public NoteRepository()
{
notes.Add(new MyNote() { ID = 1, Titel = "Morgenmad", OprettelsesDato = DateTime.Now, Note = "Spis morgenmad i dag" });
notes.Add(new MyNote() { ID = 2, Titel = "Frokost", OprettelsesDato = DateTime.Now, Note = "Spis frokost i dag" });
notes.Add(new MyNote() { ID = 3, Titel = "Aftensmad", OprettelsesDato = DateTime.Now, Note = "Spis aftensmad i dag" });
}
public void Create(MyNote mn)
{
notes.Add(mn);
}
here is the repository class with the list and the method for the create method.
and please, ask if i have missed something! Thank you :-)
It looks like you're using a List for your in-memory repository. For delete, you can implement something like this:
public bool Delete (MyNote noteToDelete) {
return notes.Remove(noteToDelete);
}
Edit: However, in this case, the list will check for reference equality. Since you have an ID, which I will assume is unique, you can instead do this:
public bool Delete(MyNote noteToDelete) {
var matchingNote = notes.FirstOrDefault(n => n.ID == noteToDelete.ID);
return notes.Remove(matchingNote);
}
You could also implement IEquatable on your MyNote class to change how your notes are compared with each other, and return a valid match when the IDs are the same.
For the IEquatable example, you would want to change the class definition for MyNote to look like:
public class MyNote : IEquatable<MyNote>
and add in the following code to the MyNote class:
public override bool Equals(object obj) {
if (obj == null) return false;
Part objAsNote = obj as MyNote;
if (objAsNote == null) return false;
else return Equals(objAsNote);
}
public bool Equals(MyNote otherNote) {
if(otherNote == null) return false;
return (this.ID.Equals(otherNote.ID));
}
public override int GetHashCode(){
return this.ID;
}
You can do something like this:
public ActionResult Edit(MyNote noteToEdit)
{
var oldNote = notes.FirstOrDefault(n => n.Id == noteToEdit.Id);
if(oldNote == null)
return View(); //With some error message;
oldNote.Title = noteToEdit.Title;
oldNote.OprettelsesDato = DateTime.Now;
oldNote.Note = noteToEdit.Note;
return RedirectToAction("Index", "Note");
}
public ActionResult Delete(int id)
{
var noteToRemove = notes.FirstOrDefault(x => x.Id == id);
if(noteToRemove == null)
return View(); //With some error message;
notes.Remove(noteToRemove);
return RedirectToAction("Index", "Note");
}
When you are editing your note, i recommend you to use AutoMapper to make your code more easy to maintain.

Passing selected value of dropdownlist as property of Model asp.net mvc

I am trying to get the selected value of three properties of my model, using dropdownlist that populate the next dropdownlist using a script.
So my problem is that I replace the EF code by this:
#Html.DropDownList("AssetID", ViewBag.AssetID as SelectList, "Select a Asset Class", new { id="AssetID" })<br />
<select id="Segment" name="segment"></select><br />
<select id="subAsset" name="SubAsset"></select><br />
Instead of that code that EF gives:
#Html.DropDownList("AssetID", String.Empty)
#Html.DropDownList("SegmentID", String.Empty)
#Html.DropDownList("SubAssetID", String.Empty)
That are three properties (foreign key) of my Model Restriction.
My problem is that now the modelState is not valid and thus the reference of Restriction is not added to the database, maybe I have to DropDownlistFor to bind the selected value to the property bu I don't know how. Also, I can post the script if needed.
My Model Restriction:
public string portefeuille
public int AssetID
public int SegmentID
public int SubAssetID
public int Min
public int Max
My Script for populating dropdown based on previous selected item:
$(function () {
$('#AssetID').change(function () {
$.getJSON('/Restriction/SegmentList/' + $('#AssetID').val(), function (data) {
var items = '<option>Select a Segment</option>';
$.each(data, function (i, segment) {
items += "<option value='" + segment.Value + "'>" + segment.Text + "</option>";
});
$('#Segment').html(items);
});
});
$('#Segment').change(function () {
$.getJSON('/Restriction/SubAssetList/' + $('#Segment').val(), function (data) {
var items = '<option>Select a SubAsset</option>';
$.each(data, function (i, subAsset) {
items += "<option value='" + subAsset.Value + "'>" + subAsset.Text + "</option>";
});
$('#subAsset').html(items);
});
});
});
Here is my RestrictionController:
public class RestrictionController : Controller
{
private RestrictionContext db = new RestrictionContext();
//
// GET: /Restriction/
public ActionResult Index()
{
var restrictions = db.Restrictions.Include(r => r.Asset).Include(r => r.Segment).Include(r => r.SubAsset);
return View(restrictions.ToList());
}
//
// GET: /Restriction/Details/5
public ActionResult Details(int id = 0)
{
Restriction restriction = db.Restrictions.Find(id);
if (restriction == null)
{
return HttpNotFound();
}
return View(restriction);
}
//
// GET: /Restriction/Create
public ActionResult Create()
{
ViewBag.AssetID = new SelectList(db.Assets, "AssetID", "Asset_Name");
/*
ViewBag.SegmentID = new SelectList(db.Segments, "SegmentID", "Segment_Name");
ViewBag.SubAssetID = new SelectList(db.SubAssets, "SubAssetID", "SubAsset_Name");
* */
return View();
}
//
// POST: /Restriction/Create
[HttpPost]
public ActionResult Create(Restriction restriction)
{
if (ModelState.IsValid)
{
db.Restrictions.Add(restriction);
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.AssetID = new SelectList(db.Assets, "AssetID", "Asset_Name", restriction.AssetID);
/*
ViewBag.SegmentID = new SelectList(db.Segments, "SegmentID", "Segment_Name", restriction.SegmentID);
ViewBag.SubAssetID = new SelectList(db.SubAssets, "SubAssetID", "SubAsset_Name", restriction.SubAssetID);
*/
return View(restriction);
}
//
// GET: /Restriction/Edit/5
public ActionResult Edit(int id = 0)
{
Restriction restriction = db.Restrictions.Find(id);
if (restriction == null)
{
return HttpNotFound();
}
ViewBag.AssetID = new SelectList(db.Assets, "AssetID", "Asset_Name", restriction.AssetID);
ViewBag.SegmentID = new SelectList(db.Segments, "SegmentID", "Segment_Name", restriction.SegmentID);
ViewBag.SubAssetID = new SelectList(db.SubAssets, "SubAssetID", "SubAsset_Name", restriction.SubAssetID);
return View(restriction);
}
//
// POST: /Restriction/Edit/5
[HttpPost]
public ActionResult Edit(Restriction restriction)
{
if (ModelState.IsValid)
{
db.Entry(restriction).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.AssetID = new SelectList(db.Assets, "AssetID", "Asset_Name", restriction.AssetID);
ViewBag.SegmentID = new SelectList(db.Segments, "SegmentID", "Segment_Name", restriction.SegmentID);
ViewBag.SubAssetID = new SelectList(db.SubAssets, "SubAssetID", "SubAsset_Name", restriction.SubAssetID);
return View(restriction);
}
//
// GET: /Restriction/Delete/5
public ActionResult Delete(int id = 0)
{
Restriction restriction = db.Restrictions.Find(id);
if (restriction == null)
{
return HttpNotFound();
}
return View(restriction);
}
//
// POST: /Restriction/Delete/5
[HttpPost, ActionName("Delete")]
public ActionResult DeleteConfirmed(int id)
{
Restriction restriction = db.Restrictions.Find(id);
db.Restrictions.Remove(restriction);
db.SaveChanges();
return RedirectToAction("Index");
}
protected override void Dispose(bool disposing)
{
db.Dispose();
base.Dispose(disposing);
}
public JsonResult SegmentList(int Id)
{
var segment = from s in db.Segments
where s.AssetID == Id
select s;
return Json(new SelectList(segment.ToArray(), "SegmentID", "Segment_Name"), JsonRequestBehavior.AllowGet);
}
public JsonResult SubAssetList(int id)
{
var subAsset = from c in db.SubAssets
where c.SegmentID == id
select c;
return Json(new SelectList(subAsset.ToArray(), "SubAssetID", "SubAsset_Name"), JsonRequestBehavior.AllowGet);
}
public IList<Segment> Getsegment(int AssetID)
{
return db.Segments.Where(m => m.AssetID == AssetID).ToList();
}
[AcceptVerbs(HttpVerbs.Get)]
public JsonResult LoadClassesByAssetId(string Asset_Name)
{
var segmentList = this.Getsegment(Convert.ToInt32(Asset_Name));
var segmentData = segmentList.Select(m => new SelectListItem()
{
Text = m.Segment_Name,
Value = m.AssetID.ToString(),
});
return Json(segmentData, JsonRequestBehavior.AllowGet);
}
}
Thank you for your help!
Firstly, you don't have getters and setter on your model properties.
Secondly, your model has properties SegmentID and subAssetID but you have named the controls Segment and subAsset so they dont match your property names. You need to name them SegmentID and SubAssetID. I strongly recommend use use the strongly typed html helper methods to prevent this, for example #Html.DropDownListFor(m => m.AssetID, ViewBag.AssetID as SelectList, ""Select a Asset Class", null)

capturing value of parameter

I really need your help on this guys I am stuck and not sure where to start the fix. So i have this form where the user can select a case and parties. I am supposed save and pass along the values of the selected items. I was able to save the case selections but i am having trouble saving the selected party. Here is my code snippets regarding gathering data and saving them.
CONTROLLER:
[HttpPost]
[ValidateInput(false)]
public ActionResult Create(VisitViewModel viewModel, Guid[] associatedCasesSelected, Guid[] selectedParties)
{
if (!ModelState.IsValid)
{
viewModel.Time = _timeEntryHelper.Value;
AddLookupsToViewModel(viewModel);
return View(viewModel);
}
var visitEntry = Mapper.Map<VisitViewModel, VisitEntry>(viewModel);
visitEntry.VisitDate = _timeEntryHelper.AddTimeToDate(visitEntry.VisitDate);
visitEntry.UserId = _currentUser.UserId;
visitEntry.OfficeId = _currentUser.OfficeId;
try
{
_visitEntryService.Create(visitEntry, associatedCasesSelected, selectedParties);
this.FlashInfo(string.Format(Message.ConfirmationMessageCreate, Resources.Entities.Visit.EntityName));
}
catch (RulesException ex)
{
ex.CopyTo(ModelState);
}
if (ModelState.IsValid)
return RedirectToAction("Edit", "Case", new { caseId = viewModel.CaseId });
AddLookupsToViewModel(viewModel);
return View(viewModel);
}
VisitEntryService:
public void Create(VisitEntry visitEntry,IList<Guid>caseIds, IList<Guid>partyIds )
{
EnsureValid(visitEntry);
_visitEntryRepository.Save(visitEntry);
caseIds = AddCurrentCaseToCases(visitEntry.CaseId, caseIds,partyIds);
foreach (var caseId in caseIds.Distinct())
{
var visit = new Visit {CaseId = caseId, VisitEntryId = visitEntry.VisitEntryId};
_visitService.Create(visit);
}
}
VisitEntryRepository:
public void Save(VisitEntry visitEntry)
{
if (visitEntry.VisitEntryId == Guid.Empty)
{
visitEntry.VisitEntryId = Guid.NewGuid();
visitEntry.DateCreated = DateTime.Now;
DataContext.VisitEntries.InsertOnSubmit(visitEntry);
}
else
{
var currentVisitEntry = Get(visitEntry.VisitEntryId);
if (currentVisitEntry == null) throw RepositoryExceptionFactory.Create("VisitEntry", "VisitEntryId");
currentVisitEntry.DateModified = DateTime.Now;
currentVisitEntry.VisitDate = visitEntry.VisitDate;
currentVisitEntry.VisitType =
DataContext.VisitTypes.SingleOrDefault(vt => vt.VisitTypeId == visitEntry.VisitTypeId);
currentVisitEntry.Note = visitEntry.Note;
}
DataContext.SubmitChanges();
}
I am not sure how to get this to save the selected party as it is saving the case information and selected case. Thanks for any feedback!
The save call is a bit earlier so your changes made after your fire SubmitChanges, move the SubmitChanges to the end you should good to go I believe
UPDATE
what I mean is change code like following and see if that helps
CONTROLLER:
[HttpPost]
[ValidateInput(false)]
public ActionResult Create(VisitViewModel viewModel, Guid[] associatedCasesSelected, Guid[] selectedParties)
{
if (!ModelState.IsValid)
{
viewModel.Time = _timeEntryHelper.Value;
AddLookupsToViewModel(viewModel);
return View(viewModel);
}
var visitEntry = Mapper.Map<VisitViewModel, VisitEntry>(viewModel);
visitEntry.VisitDate = _timeEntryHelper.AddTimeToDate(visitEntry.VisitDate);
visitEntry.UserId = _currentUser.UserId;
visitEntry.OfficeId = _currentUser.OfficeId;
try
{
_visitEntryService.Create(visitEntry, associatedCasesSelected, selectedParties);
this.FlashInfo(string.Format(Message.ConfirmationMessageCreate, Resources.Entities.Visit.EntityName));
DataContext.SubmitChanges();
}
catch (RulesException ex)
{
ex.CopyTo(ModelState);
}
if (ModelState.IsValid)
return RedirectToAction("Edit", "Case", new { caseId = viewModel.CaseId });
AddLookupsToViewModel(viewModel);
return View(viewModel);
}
VisitEntryRepository:
public void Save(VisitEntry visitEntry)
{
if (visitEntry.VisitEntryId == Guid.Empty)
{
visitEntry.VisitEntryId = Guid.NewGuid();
visitEntry.DateCreated = DateTime.Now;
DataContext.VisitEntries.InsertOnSubmit(visitEntry);
}
else
{
var currentVisitEntry = Get(visitEntry.VisitEntryId);
if (currentVisitEntry == null) throw RepositoryExceptionFactory.Create("VisitEntry", "VisitEntryId");
currentVisitEntry.DateModified = DateTime.Now;
currentVisitEntry.VisitDate = visitEntry.VisitDate;
currentVisitEntry.VisitType =
DataContext.VisitTypes.SingleOrDefault(vt => vt.VisitTypeId == visitEntry.VisitTypeId);
currentVisitEntry.Note = visitEntry.Note;
}
}

Categories

Resources