Hello i'm newbie to MVC,
i want to display webgrid in view,I'm trying to display create and display in same page,i'm getting problem at the time of displaying data in webgrid,
This is my code:
Controller:
[HttpPost]
public ActionResult Insert(Torder Model)
{
if(ModelState.IsValid)
{
try
{
ntity.Torders.Add(Model);
ntity.SaveChanges();
ModelState.Clear();
TempData["notice"] = "Successfully registered";
}
catch(Exception ex)
{
TempData["Failure"] = ex;
}
}
else
{
TempData["Failure"] = "Record Not Saved";
}
//var empoyees = Employee.GetList();
IEnumerable<Torder> model1 = GetProducts();
return View(model1);
}
public IEnumerable<Torder> GetProducts()
{
List<Torder> objStudent = new List<Torder>();
///*Create instance of entity model*/
/*Getting data from database for user validation*/
var _objuserdetail = (from data in ntity.Torders
select data);
foreach (var item in _objuserdetail)
{
objStudent.Add(new Torder { Cid = item.Cid, Ccustomername = item.Ccustomername, Citem = item.Citem, Corderamount = (int)item.Corderamount});
}
return objStudent;
}
Just pass your IEnumerable<Torder> like List<Torder> On page you can write foreach loop and create grid
--- Example:
public class Torder
{
public int Id {get;set;}
public string Name {get;set;}
}
[HttpPost]
public ActionResult Insert(Torder Model)
{
if(ModelState.IsValid)
{
try
{
ntity.Torders.Add(Model);
ntity.SaveChanges();
ModelState.Clear();
TempData["notice"] = "Successfully registered";
}
catch(Exception ex)
{
TempData["Failure"] = ex;
}
}
else
{
TempData["Failure"] = "Record Not Saved";
}
//var empoyees = Employee.GetList();
List<Torder> model1 = GetProducts();
return View(model1);
}
public List<Torder> GetProducts()
{
List<Torder> objStudent = new List<Torder>();
// your logic
return objStudent;
}
---------
Page:
-------------
//html code
#model List<Torder>
#foreach(Torder order in Model)
{
// here you can build you grid(table)
order.Name
order.Id
}
P.S In future I recommend write "clean" UI without Razor (Try learn Angular - it's really very good framework) –
It's hard to tell from code in comments, but you might just be missing the #grid.GetHtml()
The block you've shown defines the grid, but now you need to emit the HTML so something shows on the page. Put this after your #{} block right before the closing div tag.
Related
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();
}
I have an MVC Web Application which uses a form to get a postal code from the user, which then queries an external web service and returns a list of addresses to the view.
I had a previous issue whereby my model was static, therefore the data was being displayed to users on other clients, rather than being specific to each user. I have now got it so each individual user can query and get their list of addresses on the view (which isn't visible to anyone else) however, when the user refreshes the page or goes back, the data is lost.
I have some code on the page refresh which checks if the data is there and won't take the user to the start of the form, however on page refresh the model returns to null, hence it will always take them back to the beginning.
Any ideas? I ideally want to be able to use the data multiple times for the current user, but if they refresh and are say 90% through the form, they will lose the whole data. It seems like it should be easy but all of the examples I have tried haven't worked for my particular scenario.
Controller:
public class AssistedController : Controller
{
// GET: Assisted
AddressList model;
public ActionResult Index()
{
return View(model);
}
[HttpPost]
public ActionResult GetAddresses(string postcode)
{
model = new AddressList();
if (postcode == null || postcode == "")
{
return RedirectToAction("/Index/");
}
//call enviroweb web service
AddressWeb ew = new AddressWeb();
//extract address values from the XML returned from web service
XmlNode xml = ew.GetAddress(", , , , " + postcode);
foreach (XmlElement addressInfo in xml)
{
foreach (XmlElement teset in addressInfo["Addresses"])
{
//add each address item found to the list
model.listone.Add(new AddressResults {
FullAddress = teset["fulladdress"].InnerText,
Lat = teset["Lat"].InnerText,
Lon = teset["Long"].InnerText,
addLine1 = teset["addline1"].InnerText,
addLine2 = teset["addline2"].InnerText,
addLine3 = teset["addline3"].InnerText,
addLine4 = teset["addline4"].InnerText,
Town = teset["Town"].InnerText,
postcode = teset["postcode"].InnerText,
Ownership = teset["Ownership"].InnerText,
WeekNumber = teset["WeekNumber"].InnerText
});
}
}
//return the list and model back to the index view
return View("Index", model);
}
View:
<!--Use the model to return the data-->
#model AddressSearch.Models.AddressList
#{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
#if (Model == null)
{
}
else
{
if (Model.listone.Count != 0)
{
//this section returns the items as options in the select if the list count is greater than 0.
foreach (var test in Model.listone)
{
<option value="#test.FullAddress">#test.FullAddress</option>
}
}
}
Model:
public class AddressList
{
public List<AddressResults> listone = new List<AddressResults>();
}
TempData in ASP.NET MVC can be used to store temporary data which can be used in the subsequent request. TempData will be cleared out after the completion of a subsequent request.
public class AssistedController : Controller
{
// GET: Assisted
AddressList model;
public ActionResult Index()
{
if (TemData.ContainsKey("address"))
{
model = TempData["address"] as AddressList;
}
return View(model);
}
[HttpPost]
public ActionResult GetAddresses(string postcode)
{
model = new AddressList();
if (postcode == null || postcode == "")
{
return RedirectToAction("/Index/");
}
if (TemData.ContainsKey("address"))
{
model = TempData["address"] as AddressList;
return View(model);
}
//call enviroweb web service
AddressWeb ew = new AddressWeb();
//extract address values from the XML returned from web service
XmlNode xml = ew.GetAddress(", , , , " + postcode);
foreach (XmlElement addressInfo in xml)
{
foreach (XmlElement teset in addressInfo["Addresses"])
{
//add each address item found to the list
model.listone.Add(new AddressResults
{
FullAddress = teset["fulladdress"].InnerText,
Lat = teset["Lat"].InnerText,
Lon = teset["Long"].InnerText,
addLine1 = teset["addline1"].InnerText,
addLine2 = teset["addline2"].InnerText,
addLine3 = teset["addline3"].InnerText,
addLine4 = teset["addline4"].InnerText,
Town = teset["Town"].InnerText,
postcode = teset["postcode"].InnerText,
Ownership = teset["Ownership"].InnerText,
WeekNumber = teset["WeekNumber"].InnerText
});
}
}
TempData["address"] = model;
//return the list and model back to the index view
return View("Index", model);
}
}
Refer this link to how to use
i have 2 actions .. one for User and i can add data to User table but for Order table my code didn't works and got catch error
this is my user code (Action in Controller)
[HttpPost]
public ActionResult Register(User user)
{
UserRepository blUser = new UserRepository();
if (ModelState.IsValid)
{
if (blUser.Add(user))
{
return Json(new JsonData() { Success = true });
}
else
{
return Json(new JsonData() { Success = false });
};
}
else
{
return Json(new JsonData() { Success = false });
}
}
and (UserRepository):
public class UserRepository : IDisposable
{
private HairCut.Models.MVCHairDresserDBEntities db = null;
public UserRepository()
{
db = new HairCut.Models.MVCHairDresserDBEntities();
}
public bool Add(HairCut.Models.User entity, bool autoSave = true)
{
try
{
db.Users.Add(entity);
if (autoSave)
return Convert.ToBoolean(db.SaveChanges());
else
return false;
}
catch
{
return false;
}
}
i just change User word to Order but when try to insert data to table i got catch and return false
Order code:
[HttpPost]
public ActionResult Reserve(int select, int user,int hdId)
{
Order order = new Order();
order.HairDresserId =hdId;
order.UserId = user;
order.timeCome = (select).ToString();
order.timeNow = DateTime.Now.ToString("dddh");
order.confirm = true;
OrderRepository blOrder = new OrderRepository();
if (blOrder.Add(order))
{
return Json(new JsonData() { Success = true });
}
else
{
return Json(new JsonData() { Success = false });
}
}
OrderRepository is similar UserRepository. so why cant insert ? where is my wrong ?
every time use breackpoint and debug my codes got catch in code return Convert.ToBoolean(db.SaveChanges());
OrderRepository have 2 foreignkey. when i checked entity quick watch, helper show me 2 extra field ( User and HairDresser with null value ) .. maybe i need set value to these ?
or maybe need create MetaData class to check validation like User values ( but i don't think this is my problem )
Here is my codes I just want to show on html page. I couldn't understand how to bind it. What do I have to use in HTML page inside foreach and above !DOCTYPE html.Actually I want to check that the IP Address and I want to show if it is online or not via Ping. Thanks for your help.
public class HomeController : Controller
{
private PrinterEntities db = new PrinterEntities();
public ActionResult Index()
{
List<string> catlist = new List<string>();
foreach (var item in db.C_Network)
{
if (CheckInternetConnection(item.IPAdresi))
{
catlist.Add(item.IPAdresi);
}
}
return View(catlist);
}
public bool CheckInternetConnection(string HostName)
{
bool result = false; // assume error
try
{
Ping oPing = new Ping();
PingReply reply = oPing.Send(HostName);
if (reply.Status == IPStatus.Success)
{
result = true;
}
}
catch (Exception E)
{
}
return result;
}
}
<div>
<ul>
#foreach (var item in Model)
{
#if ()
{
}
}
</ul>
</div>
I suggest:
public class HomeController : Controller
{
private PrinterEntities db = new PrinterEntities();
public ActionResult Index()
{
List<string> catlist = new List<string>();
foreach (var item in db.C_Network)
{
if (CheckInternetConnection(item.IPAdresi))
catlist.Add(item.IPAdresi);
}
}
ViewData["List"] = catlist;
return View();
}
You can get the list in aspx byList<string> Cats = (List<string>)ViewData["List"]; and iterate in for loop
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;
}
}