MVC data passing in view - c#

I am making my MVC application. I open my view with predefined parameters like this:
return RedirectToAction("PickGroupForHomework", "Account", new {subject_id = id, qty=model.qty });
And this works fine, the data subject_id and qty are passed correctly. However, my view PickGroupForHomework contains a form to fill, which is then validated. If the input is not valid, the window simply should reload with the data subject_id and qty as defined in previous view. I do this in such way:
public ActionResult PickGroupForHomework(PickGroupForHomeworkViewModel model)
{
ClassDeclarationsDBEntities2 entities = new ClassDeclarationsDBEntities2();
model.groups = entities.Groups.ToList();
model.users = entities.Users.ToList();
int id = model.subject_id;
var subj = entities.Subjects
.Where(b => b.class_id == model.subject_id)
.FirstOrDefault();
if (subj != null)
{
model.subject_name = subj.name;
}
if (ModelState.IsValid)
{
}
else
{
return View(model);
}
return View(model);
}
But the resulting URL does not contain the data I need, but just a plain view. How do I do it right?

In order for you wep app to work, you will need two actions, one to set your model up for the View and another to actually do the work to post and save your data:
public ActionResult PickGroupForHomework(int subject_id, int qty)
{
//Initialize your model here. Below is just an example.
ClassDeclarationsDBEntities2 entities = new ClassDeclarationsDBEntities2();
PickGroupForHomeworkViewModel model = new PickGroupForHomeworkViewModel();
model.groups = entities.Groups.ToList();
model.users = entities.Users.ToList();
model.subject_id = subject_id;
model.qty = qty;
return View("PickGroupForHomework", model);
}
[HttpPost]
public ActionResult PickGroupForHomework(PickGroupForHomeworkViewModel model)
{
ClassDeclarationsDBEntities2 entities = new ClassDeclarationsDBEntities2();
int id = model.subject_id;
var subj = entities.Subjects
.Where(b => b.class_id == model.subject_id)
.FirstOrDefault();
if (subj != null)
{
model.subject_name = subj.name;
}
if (ModelState.IsValid)
{
//Save to database
[code goes here]
//return to a View to show your results
return View("[Your view to see the results]")
}
//Model Validation did not pass
//or exception occurred go back to View
return View(model);
}

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();
}

MVC reusing model

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

Show buttons on a partial view based on some query

I am showing search results same as searching groups on facebook
enter image description here
I have a relationship Table named CommunityUser in Database having attributes CommunityID and UserID.
Using Partial View I want to show if User not already joined that Community/Group that it will show Join Button else if user already joined that community it will show Leave button.
I have written IsMember() function in my controller that takes two parameters, CommunityID and UserID. This will return true if that Community ID exist against that user ID.
public bool IsMember(string UserID, int CommunityID) {
var Membership = db.Users.Include(x => x.CommunityUsers).Where(s => s.Id.Equals(UserID)).Count();
if(Membership>0)
return true;
else
return false;
}
Now what I actually need is, I want to call this function in an IF condition on my view class. It is not allowing me to call this function on my view Class.
#if (){
<button>#Html.ActionLink("Leave", "LeaveCommunity", new { id = ViewBag.ComID })</button>
}
else
{
<button>#Html.ActionLink("Join", "joinCommunity", new { id = ViewBag.ComID })</button>
}
In your controller you should have a method which will return this view. So in this method you call this function
public ActionResult Index(string UserID, int CommunityID)
{
var hasMembership = IsMember(serID, CommunityID);
return View(hasMembership);
}
In the View it self then you just grab this variable hasMembership you just passed from #model.
#if (Model){
<button>#Html.ActionLink("Leave", "LeaveCommunity", new { id = ViewBag.ComID })</button>
}
else
{
<button>#Html.ActionLink("Join", "joinCommunity", new { id = ViewBag.ComID })</button>
}
Note: it might be wise to create some DTO class for passing data to a view, because you might need to pass multiple value to a view at some point. Plus the whole condition would be more readable
public SomeDTO {
public bool IsMember {get;set}
public List<Community> Communities {get;set;}
}
public ActionResult Index(string UserID, int CommunityID)
{
var hasMembership = IsMember(serID, CommunityID);
var listOfCommunities = _repo.GetComunities();
var dto = new SomeDTO
{
IsMember = hasMembership,
Communities = listOfCommunities
}
return View(dto);
}
#if (Model.IsMember){
// do or do not something
}

passing data between controller methods

I'm creating asp.net mvc 5 application. in this application I have faced to problem passing data between controller methods.
Here the scenario step by step
I'm getting IEnumerable dataset to Create_Brochure method like this
public ActionResult Create_Brochure(IEnumerable<ProductsPropertiesVM> model)
{
IEnumerable<BrochureTemplateProperties> sample = model.Where....
return View(sample);
}
Then I need to save that IEnumerable<ProductsPropertiesVM> model to another IEnumerable object and use that in Create_Brochure_PDF() method
public ActionResult Create_Brochure_PDF()
{
IEnumerable<BrochureTemplateProperties> samplePDF = modelPDF....
return View(samplePDF);
}
for that I'did bit R&D part and came up solution with Sessions , Here the tutorial I followed
So I changed my code like this
but seems I'm having compile time errors though I followed exact as tutorial
1st controller method
[HttpPost]
[ValidateInput(false)]
public ActionResult Create_Brochure(IEnumerable<ProductsPropertiesVM> model)
{
IEnumerable<ProductsPropertiesVM> modelPDF = new IEnumerable<ProductsPropertiesVM>();
modelPDF = model;
IEnumerable<BrochureTemplateProperties> sample = model.Where(y => y.IsChecked)
.Select(y => new BrochureTemplateProperties
{
Property_ID = y.Property_ID,
IsChecked = y.IsChecked,
Property_Title = y.Property_Title,
Property_Value = y.Property_Value
});
TempData["TemplateData"] = modelPDF;
return View(sample);
}
2nd controller method
public ActionResult Create_Brochure_PDF()
{
IEnumerable<ProductsPropertiesVM> modelPDF = TempData["TemplateData"] as IEnumerable<ProductsPropertiesVM>;
IEnumerable<BrochureTemplateProperties> samplePDF = modelPDF.Where(y => y.IsChecked)
.Select(y => new BrochureTemplateProperties
{
Property_ID = y.Property_ID,
IsChecked = y.IsChecked,
Property_Title = y.Property_Title,
Property_Value = y.Property_Value
});
return View(samplePDF);
}
You can not instantiate interface..!
Replace
IEnumerable<ProductsPropertiesVM> modelPDF = new IEnumerable<ProductsPropertiesVM>();
modelPDF = model;
With
IEnumerable<ProductsPropertiesVM> modelPDF = model;
inside your Create_Brochure method.

Prepopulate HtmlTextBoxFor with value from another field?

I have a web page that is using a number of different partial views and different viewmodels for each partial. One of the partials is for the ability for a user to change their username. Since we are going to allow email addresses as usernames now, I would like to pre-populate the textbox with their current email address from another partial view on the page. How can this be done properly so the value will be populated in the text box and then saved when the submit to the controller happens? Here is a brief code snippet from what I'm looking at:
The view:
#Html.TextBoxFor(model => model.NewUsername, new { id = "uName_change" }) #Html.ValidationMessageFor(model => model.NewUsername)
It's worth noting here that I have tried setting the current email address into ViewData and ViewBag and putting "#value = viewdatahere" into the textbox for properties, but this didn't populate the string, it just left it blank.
I just need to know how this is done. Any help is appreciated.
Edit to add controller POST and GET methods:
[HttpGet]
[ClaimsPrincipalPermission(System.Security.Permissions.SecurityAction.Demand, Resource = Resources.User, Operation = Operations.Edit)]
public ActionResult ChangeUsername(Guid uniqueUserId)
{
User user = UserManager.GetUser(uniqueUserId);
AuthorizationHelper.ConfirmAccess(Resources.User, Operations.Edit, user);
ChangeUsername model = new ChangeUsername(){UserGuid = user.Identifier,NewUsername = user.Username};
return View(model);
}
[HttpPost]
[ClaimsPrincipalPermission(System.Security.Permissions.SecurityAction.Demand, Resource = Resources.User, Operation = Operations.Edit)]
public ActionResult ChangeUsername(ChangeUsername changeUsername)
{
User usr = UserManager.GetUser(changeUsername.UserGuid);
AuthorizationHelper.ConfirmAccess(Resources.User, Operations.Edit, usr);
if (!ModelState.IsValid)
{
return View(changeUsername);
}
//setup request
SupportUser su = (SupportUser)ViewData["SupportUser"];
RequestData rqd = new RequestData(GetApplicationIdentifer(usr), su.clientIP, su.lanID);
UserUsernameChangeRequest request = new AdminUsernameChangeRequest(rqd,usr,changeUsername.NewUsername);
UserUsernameChangeResponse response = UserManager.ChangeUserUsername(request);
if (response.Status == UserProcessorStatus.Success)
{
var message = ("User has been updated successfully");
TempData["message"] = message;
return PartialView("_NewUsername", changeUsername);
}
switch (response.Status)
{
case UserProcessorStatus.DuplicateUsername:
{
ModelState.AddModelError("NewUsername", "Duplicate username");
changeUsername.AlternateUsernames = response.AlternateUsernames;
return PartialView(changeUsername);
}
default:
{
ModelState.AddModelError("NewUsername", String.Format("An unexpected error occured. Error Code:{0}, Message:{1}", response.Status, response.Message));
return PartialView(changeUsername);
}
}
}
There it is.
The last time that I tried to do this was with MVC 3, but I do know that this technique worked then. It's a stupid difference, that's why I pointed that out first.
You were very close with your attempt at it, but you need to set the property as #Value, not #value. I never looked to hard into why the capital made a huge difference. (Like I said, it's a stupid difference.)
var val = "Dummy Value";
#Html.TextBoxFor(model => model.NewUsername, new { id = "uName_change", #Value = val })
Here's how I'd do it.... in the main page set up a viewmodel that contains the other view models like this:
public class VMMain(){
public void VMMain(){
//don't forget null CTOR as MVC requires it...
}
public void VMMain(Guid userguid, string newusername){
UserGuid = userguid;
NewUserName = newusername;
Part1 = new VM1(UserGuid, NewUserName);
Part2 = new VM2();
Part3 = new VM3();
}
public VM1 Part1 {get;set;}
public VM2 Part2 {get;set;}
public VM3 Part3 {get;set;}
Guid UserGuid {get;set;}
string NewUsername {get;set;}
}
In your main view you can bind to anyone of these viewmodels and properties within them. Just make sure you have a property available to bind.
This would change your controller to look like this:
[HttpGet]
[ClaimsPrincipalPermission(System.Security.Permissions.SecurityAction.Demand, Resource = Resources.User, Operation = Operations.Edit)]
public ActionResult ChangeUsername(Guid uniqueUserId)
{
User user = UserManager.GetUser(uniqueUserId);
AuthorizationHelper.ConfirmAccess(Resources.User, Operations.Edit, user);
var model = new VMMain(){UserGuid = user.Identifier,NewUsername = user.Username};
And now you can bind to say Partial ViewModel 1 that has that property like this:
#Html.TextBoxFor(p => model.Part1.NewUsername,
new { id = "uName_change" })
#Html.ValidationMessageFor(p => model.Part1.NewUsername)
return View(model);
}

Categories

Resources