I have a basic CRUD application in ASP.Net MVC 4. The Create view of the CRUD format has a form with "save" and "cancel" buttons. When I click on save button, the data are stored correctly in the database and the view refresh to the previous list records.
I want to make a "save and add" button where the user click on it and then the data will stored and load again the "create" view.
Sorry my bad english...
Thanks.
To mfanto's point, if you wanted to be able to detect, as I believe you do, which button was clicked, just create both buttons with type="submit" and both with the same name. However, give them both different values. Like:
<input type="submit" name="whichButton" value="Save" />
<input type="submit" name="whichButton" value="SaveAndAdd" />
Then in your controller, you'll receive the button value in a parameter named the same as the button:
public ActionResult ActionName(Model model,string whichButton){
switch(whichButton) {
case "Save" : //do stuff and redirect to the list of records
break;
case "SaveAndAdd" : //do stuff and redirect to create
break;
}
}
You need to change the redirection in your Create action. This is called the Post/Redirect/Get pattern. When you POST your form data, your action will save it to the database, and then redirect somewhere else. Right now it's redirecting you to your list of items action (maybe RedirectToAction("Index")). Change it to redirect back to Create.
public ActionResult Create(DataModel data)
{
if (ModelState.IsValid)
{
// save data here
return RedirectToAction("Create");
}
}
Related
OK, I have a form where the data is persisted into database with create/edit.
On edit page there is a checkbox with name audit_check which is clicked by a user and the logs should be generated.
if($form->isSubmitted()){
if(user checks){
//create logs
}else{
//do nothing
}
$em->persist($data);
$em->flush();
}
Since the requirement of the task is to generate click logs and checkbox is rarely clicked while the pages is often edited. How to get the user click behavior such that when the user checks/uncheck the logs must be generated that the user clicked the checkbox.
You could keep track of clicks made on such checkbox and submit that value together with the form data when it gets submitted. One way to achieve that would be having an hidden input like this:
<input type="hidden" id="clicksMade" name="" value="0" />
inside such form so that you'll have its value in the update action in the controller when the form gets submitted.
To update your click counter client side before the user submits the form (I used jQuery here I hope you don't mind):
$(document).ready( () => {
$('#audit_check').on('change', () => {
let i = parseInt( $('#clicksMade').val() );
$('#clicksMade').val(++i);
});
});
I am a beginner and currently started a small project for my study purpose. A mini DB search portal. I created front end View. It has one search box and a button. Now what I need is, I have to fetch the data from DB, related to the user entered search term on clicking on the button.
How to proceed to get the user entered data from view to controller and process it for further operations.
General code:
view:
#using(Html.BeginForm("Search","Test"))
{
<input type="text" name="txtName"/>
<input type="submit" value="Generate report" />
}
Controller
[HTTPPost]
public ActionResult Seacrh(FormCollection form) // "Search" is action name specified in view for controller "TestController"
{
string text = form["txtName"]; // txtName is name of input in view.
}
However to take full advantage to MVC have a look at Model Binding in MVC
I recommend reading this article, it has an example different ways of adding search.
You can update the Index method in your Controller and View as follows:
1)Add a form to the view that will post to the view itself
View
#using (Html.BeginForm()){
<p> Title: #Html.TextBox("SearchString") <br />
<input type="submit" value="Filter" /></p>
}
2)Add a parameter to the Index method to filter the content based on the parameter passed. public ActionResult Index(string searchString)
Controller
var movies = from m in db.Movies
select m;
if (!String.IsNullOrEmpty(searchString))
{
movies = movies.Where(s => s.Title.Contains(searchString));
}
return View(movies);
I just want to make a search for my site , and before I start work on that I just want to sort my work steps .
My site type is books site . and here is what I want to know :
I have a search box in my navbar .
when someone entered a book name to search I want to show the result of this
search in this page :
Localhost/Search?string=C++
How I can call the method that will process the search from the view
?
How should the controller method looks like , also the view page.
How to make a paging to the search page ?
I don't need a code , I just want from someone to help me with a list of steps I should do , to make the search as I requested and thanks a lot guys ....
You can keep your input box for search inside a form and keep the form's method value to be GET.
#using (Html.BeginForm("Search", "Students", FormMethod.Get, null))
{
<input type="text" name="searchTerm" />
<input type="submit" />
}
Now you should have an action method called Search inside your StudentsController which accepts a string value in a parameter named searchTerm.
public ActionResult Search(string searchTerm)
{
// use searchTerm variable to get data and pass to view
return View();
}
Now in your view (~/Views/Students/Search.cshtml), you can use the passed data to display the search results.
For paging, you may add another parameter to your action method which you will use to get a specific sub set of the data.
public ActionResult Search(string searchTerm,int page=1,size=10)
{
// use searchTerm variable to get data and pass to view
// page number is in page variable
// size is in size variable
return View();
}
Now you need to adjust your view to show all the page numbers and link to the same action method and pass the page number in url like
/Students/Search?searchTerm=Java&page=2&size=25
Usually, in ASP.NET, MVC or otherwise, we make the client download a file by having the user click a link/button; I assume this link/button action goes to the correct controller then redirects back to the main page. However, how can I cause the download from some intermediate controller, during a series of redirects?
Basically, when the user clicks a button to create a PDF, the action goes to PdfController to create the PDF, then, since I'm assuming he/she wants to download the PDF anyway (if he/she doesn't, he/she can always click "No"), I want to have the browser download the PDF before the page gets rendered again. If I haven't lost you yet, how do I accomplish this?
Here's a sample of what I have so far. Button that starts the action:
<a class="btn btn-primary col-md-2 col-md-offset-1" href="#Url.Action("MakePdf", "Pdf")">Create PDF</a>
PdfController's MakePdf() method:
public ActionResult MakePdf()
{
string PdfUrl = Environment.GetEnvironmentVariable("HOMEDRIVE") + Environment.GetEnvironmentVariable("HOMEPATH") + "/Sites/Bems/PDF/UserPdfs/report" + Id + ".pdf";
// create the PDF at this PdfUrl
return RedirectToAction("ShowPdf", "Pdf", new { PdfUrl = PdfUrl });
}
PdfController's ShowPdf() method, redirected from the previous MakePdf() method:
public ActionResult ShowPdf(string PdfUrl)
{
if (System.IO.File.Exists(PdfUrl))
{
return File(PdfUrl, "application/pdf"); // Here is where I want to cause the download, but this isn't working
}
else
{
using (StreamWriter sw = System.IO.File.CreateText(PdfUrl))
{
sw.WriteLine("A PDF file should be here, but we could not find it.");
}
}
return RedirectToAction("Edit", "Editor"); // Goes back to the editing page
}
I'm trying to cause the download at the place in the code I specified, but I'm not sure how to cause it. Usually you return it somehow to the view, whereas here I'm calling an object, I think, but I'm really fuzzy on how that all works. Regardless, something I'm doing isn't working. Any ideas on what that is?
You can't return the ViewResult RedirectToAction("Edit", "Editor") and in the same response a FileResult File(PdfUrl, "application/pdf")
To accomplish your task you could follow this scenario:
click on button create pdf
call the RedirectToAction("Edit", "Editor");
in this case at the end of the view, add a javascript call to the action method returning the FileResult
once the page is rendered, the download will start automatically
There is an asp.net mvc 4 website. The users want to re-start the web application from scratch. What's the best way to clear all the login/membership information. Just use Sql server management studio to delete the records in all the tables? (webpages_*, and UserProfile)?
There is an added column in table UserProfile which refers to an user defined table.
Or maybe just drop the whole database using SSMS? Or delete all the tables (include the __MigrationHistory) in the database?
In the controller you use for handling the users, you can create an action method to delete a user. In this example it's the current user that will be deleted, including all related data.
public ActionResult DeleteMe()
{
Membership.DeleteUser(User.Identity.Name, deleteAllRelatedData: true);
FormsAuthentication.SignOut();
return RedirectToAction("Login", "Account");
}
To call the action method above just add the following code in a view to display a button...
#using (Html.BeginForm("DeleteMe","Account"))
{
#Html.AntiForgeryToken()
#Html.ValidationSummary()
<fieldset>
<input type="submit" value="Delete my account" />
</fieldset>
}
...or this, if you want to display a link.
#Html.ActionLink("Delete my account", "DeleteMe", "Account")
If you want the function to delete another user and not yourself you can modify the action method above and do something like this:
public ActionResult DeleteUser(string userName)
{
Membership.DeleteUser(userName, deleteAllRelatedData: true);
}
Note that you need to add a bit more of security to this to check that the user calling this method actually has the right to do it...but this is the basics regarding how to delete a user.