MVC Display Offences List By User State - asp.net-mvc

I am just starting learning MVC and I am stuck on this issue. I will appreciate if anyone has come across this before. Thanks
I would like to display the list by station. E.g Police of New-York can only see list of offences in New-York.
enter image description here This is the most recent change but still not working.
I would like to display the list of offences by the USER state.
At the moment I am displaying all the users regardless of their state id.

Here are two options that come to mind. One, you can filter out the offenses by iterating over them and pulling out only the values you need into a new list in C#. Two, you could edit the stored procedure to pass in parameters (such as a State ID or User ID) and then filter out the list of offenses returned from the database using a WHERE clause. Below is some sample code based on your image.
Idea One:
public ActionResult ViewOffenceList(int filterStateID)
{
PageModel model = new PageModel();
DBFile db = new DBFile();
var details = db.Offence.ToList();
List<Offence> filteredList = new List<Offence>();
foreach (var offence in details)
{
if (offence.StateID == filterStateID)
{
filteredList.Add(offence);
}
}
model.OffenceList = filteredList;
return View(model);
}
Idea Two:
CREATE PROCEDURE dbo.fwsp_GetOffenceList
#FilterStateID TINYINT
AS
SELECT *
FROM dbo.offences o
WHERE o.StateID = #FilterStateID
GO
These are just some quick overviews of the two options that come to mind given my experiences. In general, grab the ID of the state you wish to filter on, and use that to filter out which data to actually display. It sounds like you may have a User object which may have an associated State which you could use as the "filterStateID" in my examples.
If you're just starting out I'd suggest finding some tutorials online and walking through them. Here's one directly from Microsoft: https://learn.microsoft.com/en-us/aspnet/core/tutorials/first-mvc-app/start-mvc?tabs=aspnetcore2x

Related

Can I append data from controller to url and still render same page?

I have a simple MVC application that presents an IQ test to the person.
I have a controller call TestMyIQController and on this controller I have three action methods and corresponding to three views.
1) Index.cshtml
2) Questions.cshtml
3) Score.cshtml
On the first page localhost:12345/TestMyIQ/Index of the application I ask the user to input their First and Last name and click button Next to go to second page.
On the second page of the application localhost:12345/TestMyIQ/Questions I present a few multiple choice questions and I have the user select True/False for each question. Once the user complete all the question she can click button Submit to see her IQ score.
On the final score page localhost:12345/TestMyIQ/Score I show the score via a ViewBag object.
However, I want to know how to modified the final page url so that I can append the First Name of the user? For example if the person name is John Doe then I want my final score url will be like this localhost:12345/TestMyIQ/Score?firstname=John.
Note it is not necessary to append the First Name to all other url...because I only want it on the final score page.
Please help me. Thanks
Considering you received the first name in the Questions action, and added as a property of your model, you can add it to your form as a hidden field:
Questions.cshtml
using(Html.BeginForm())
{
#Html.HiddenFor(x => x.UserFirstName);
// rest of form
}
TestMyIQController
[HttpPost]
public ActionResult Question(QuestionModel model)
{
// form processing
return RedirectToAction("Score", new{ firstName = model.UserFirstName })
}
Because in the Question page you stored it as a hidden field, it will only show up in the url of the score page.
But keep in mind that while this is ok if you're learning and just want to do some cool stuff to show your friends, this isn't the best way to handle all of this.
EDIT to add more info on the problems of using this method.
The negative is that anyone can change the URL. Nothing stops me from changing ?firstName=foo to ?firstName=bar. Second, names can contain invalid characters for URLs, which will need to be encoded. Third, it's overall bad design.
There are better ways to handle this, but it depends on the what you need from it. Will the users be able to share the url? If not, you can add it to the Session. This is definitely easier to implement in your current design. If they'll do, you could store the result in a SQL table, and share the url as ?scoreId=f88f9426-04d7-4ae2-8e15-a4bbd8d6faad.
Not sure I understand your needs, but you dont have to store the name in url, you can use for example session variable, but if you insist on it being on url, why not just redirect(urlWithParameter).
For a good listing of possibilities, see
Msprogrammer
Session may be choice to store the name and retrieve it on the score page.
[HttpPost]
public ActionResult Index(UserModel model)
{
// save the name
Session["FirstName"] = model.FirstName;
return RedirectToAction("Questions")
}
On the score method, retrieve the name from session
[HttpPost]
public ActionResult Score(ScoreModel model)
{
// save the name
string firstName = (string)Session["FirstName"];
return RedirectToAction("Index")
}
Hope it helps.

I'm having troubles getting drop-down-menus in MVC to return data

I am very new to MVC as a whole, and I was sent to create a web application that would give the user options then change the view based on these options. First I created a simple "select" html drop down menu but I am under the assumption that this won't work.
I can supply all the actual code I currently have, I just don't know what would be important to see and what would just be bothersome to wade through.
When I had created a constructor for the model, it wouldn't go through that constructor or else it would be easier.
Sorry since this all sounds probably bad, but any help would be amazing.
There are couple ways to do that , here's what i do :
create the function in your controller (The one that returns the list of items you want to include in the dropdownmenu) . let's name it getNames();
Then return that to the view using #viwbag.Names;
In the view you can declare a variable , something like:
#{
SelectListItem[] Names = ViewBag.Name;
}
and the dropdown menu code should be something like this:
#Html.DropDownList("Names", Names)
Finally, here is sample code for the controller:
IEnumerable<SelectListItem> Names =
(from names in YourDB.students.ToArray()
select new SelectListItem
{
Text = names.Name,
Value = names.Id
}).ToArray();
var Templist = names.ToList();
ViewBag.Roles = Templist.ToArray();

PetaPoco complex types posting to controller

As per a question that I asked yesterday I was trying to find a way to dynamically create more text boxes and have those map to my view's model so upon post to the server it will grab all the dynamically(js) generated text boxes and post that to an object such as a List.
To give an example of this confusing question:
I have a textbox that is labeled "Primary Contact" and the ticket creator can enter the contacts name and phone number into this box. What I want to do essentially is, switch this to three text boxes. One for Name, Email and PhoneNumber instead of one box. Then I will create some javascript that will dynamically create three more boxes to add another contact to this List collection. Then when the user submits the form to modify or create the ticket it passes this collection inside the model to the controller. However with petapoco it is a little confusing. Let me show you the controller:
[HttpPost]
public ActionResult ModifyTicket(Ticket model)
{
string userString = User.Identity.Name.Replace("ONHOLD\\", "");
if (ModelState.IsValid)
{
model.CreatedDate = DateTime.Now;
model.LastUpdateBy = Util.GetEmployeeIdByName(userString);
model.LastUpdate = DateTime.Now;
model.IsComplete = false;
model.ClientString = Util.GetClientNameById(model.ClientId);
model.LocationString = Util.GetLocationNameById(model.LocationId);
model.Update();
SuccessMessage = "You have successfully updated ticket number: " + model.TicketId + " for the following client: " + model.ClientString + ".";
return RedirectToAction("Index");
}
ErrorMessage = "Woops! Something went wrong, please check back in a few moments, if the problem persists please contact development.";
return RedirectToAction("Index");
}
The simple answer to this would be that my database model would contain a List object for this exact reason. However, I am using PetaPoco and I'm not entirely sure how it would be done. I could manually add in a collection to my Database model but when I regenerate my model based on any database schema changes I will lose any changes I've made to the file.
I am also using a partial class that my view uses for validation using DataAnnotations. However this class is identical to the database model it just contains DataAnnotations to provide client-side validation.
If anyone understands what I'm trying to accomplish I would be more than happyto provide more information to clarify any missing pieces. I just need a resolution to this as I can't find a solid way to go about resolving this issue!
Not entirely sure what you mean but it's easy to model bind from/to a list with MVC as you may already know. As for saving a deep object like this I'd use the [Ignore] attribute on the Ticket.List so it isn't persisted and handle it separately. I'd load the Contacts in separately from the Ticket object then manually add them to the Ticket object, alternatively use a join query and try the one-to-many approach to load it all in one go.
I think you're expecting Petapoco to update all in one? This won't happen you'll need to break it up. Hard to say from what you've written so far. There won't be a long list of contacts (from the sounds of it) so just insert or update them one by one.
Well that might help, or might not.

Is it possible to name (or tag) FormStack fields with simple identifiers?

This question assumes familiarity with FormStack, a drag-and-drop WYSIWYG online form builder.
Background
A client is using FormStack to manage forms. Currently, form submissions are emailed, then manually entered into a database. Predictably, my task is to automate this process. This is easy enough using FormStack's WebHooks API: I can have form submissions sent to a URL, e.g. a PHP script, and happily parse away.
Question
Is it possible to name (or tag) FormStack fields with simple identifiers?
The client needs to be able to customize the form such that multiple fields may feed into the same database column.* FormStack however, as far as I can tell, provides only a way to specify a field label, e.g. Which of these trips interest you?, not a programmer-friendly identifier, e.g. Trip. My script would have to string-compare labels (which, due to their length, are more prone to typos) to determine what to do. What are some sensible workarounds to this problem?
Clarifications*
The reason there can exist multiple fields that feed into the same database column, is that the client uses conditional fields. For example, one field might ask, Where are you studying abroad? If the user selects "Europe", a conditional field might appear, asking Which of these trips interest you?, with choices pertaining to Europe. If the user selects "Africa" however, a similar field might appear, e.g. Which of these trips interest you?, but with choices pertaining to Africa. In FormStack, these are actually two distinct fields. However, as you can imagine, the values belong in the same database column, Trip.
I have settled on a hack for now. FormStack allows HTML markup in labels, e.g. Which of these trips interest you? <!--Trip-->. The client is willing to "tag" fields in this way.
Here's a snippet of the code that parses such tags, in case it might help someone else:
require_once 'Formstack.php';
$formstack = new Formstack($apiKey);
$form = $formstack->form($_POST['FormID']);
$taggedFields = array();
foreach ($form['fields'] as $field)
{
if (preg_match('/<!--\s*([0-9A-Za-z]+)\s*-->/',
$field['label'],
$matches))
{
$taggedFields[$matches[1]] = $_POST[$field['id']];
}
}
In fact, I've had to make it a little bit more sophisticated. Some FormStack field-types serialize input (in a horrific way). For example, FormStack's Name field-type takes multiple fields (prefix, first, middle, last, initial, suffix), and concatenates the results into a string:
'first = Andrew
initial = W
last = Cheong'
To handle this, I've written my code to handle such syntax in labels as Tell us your name! <!--FirstName=first--> <!--LastName=last--> <!--MiddleInitial=initial-->
The code follows.
require_once 'Formstack.php';
$formstack = new Formstack($apiKey);
$form = $formstack->form($_POST['FormID']);
$taggedFields = array();
foreach ($form['fields'] as $field)
{
if (preg_match_all('/<!--\s*([0-9A-Za-z]+)\s*(?:=\s*(\w+))?-->/',
$field['label'],
$matches,
PREG_SET_ORDER))
{
foreach ($matches as $captures)
{
if (count($captures) == 3 &&
preg_match('/(?:^|\n|\r)'.$captures[2].' = ([^\n\r]+)/',
$_POST[$field['id']],
$subcaptures))
{
$taggedFields[$captures[1]] = $subcaptures[1];
}
else
{
$taggedFields[$captures[1]] = $_POST[$field['id']];
}
}
}
}
Hopefully, FormStack will soon add a native way to name or tag fields!

asp.net-mvc - how do i create a view to show all unapproved users and allow them to be approved

i have this code in my membership service class (taken from the asp.net-mvc sample app)
public MembershipUserCollection GetUnapprovedUsers()
{
MembershipUserCollection users = Membership.GetAllUsers();
MembershipUserCollection unapprovedUsers = new MembershipUserCollection();
foreach (MembershipUser u in users)
{
if (!u.IsApproved)
{
unapprovedUsers.Add(u);
}
}
return unapprovedUsers;
}
i now need a view to show this list of information and allow someone to approve them which will go back to the controller and set the IsApproved property to true.
Create a view which will generate a form containing label and checkbox for each member of the collection. You need to be able to get from the id of the checkbox to the user.
In the HTTP.POST Action method, iterate through the submitted fields looking for set checkboxes, when you find one set the corresponding user to approved.
Obviously the form can display arbitrary details for each user.
To use the inbuilt control helpers takes a bit more effort because you don't have a fixed size model to work with. To achieve something similar I:
Used a non-strongly typed view
populated ViewData["ids"] with IEnumerable<IdType> (which the view would loop over)
For each entry populated ViewData["field" + id] for each field I was displaying in the entity
In the view looped over the ids using ViewData["ids"] to call the HTML helpers with the id of the field.
(That was V1, in V2 I used model state so I could use the inbuilt validation error display support, but that doesn't really apply if you just want to select users.)
The POST processing was similar, repopulating the id list from the database and the looking up in the passed FormCollection.

Resources