Show message for insert and update data in index view page - c#

In my ASP.NET MVC application, we have
public ActionResult Create(parameters)
{
if (ModelState.IsValid)
{
//code block
return RedirectToAction("Index");
}
}
This is the method for data insert:
public ActionResult Edit(int? id)
{
if (ModelState.IsValid)
{
//code block
return RedirectToAction("Index");
}
}
and I also have a method for data edit.
On successful insert/edit, I am calling
return RedirectToAction("Index");
I want to show a message "data inserted successfully" for create method and "data updated successfully" for update method.
Is it possible to show such a message on the Index page, or is there any other way I can show message to the user for these two successful operations?

1. There is no problem to pass a string as a model to the view:
public ActionResult Index(string message)
{
return View((object)message);
}
public ActionResult Create(/*parameters*/)
{
if (ModelState.IsValid)
{
//code block
return RedirectToAction("Index", new { message = "Data inserted successfully" });
}
return View();
}
public ActionResult Edit(int? id)
{
if (ModelState.IsValid)
{
//code block
return RedirectToAction("Index", new { message = "Data updated successfully" });
}
return View();
}
And the Index.cshtml:
#model System.String
#{
ViewBag.Title = "Home Page";
var text = (Model is string) ? Model : String.Empty;
}
#if (!String.IsNullOrEmpty(text))
{
<div class="jumbotron">
<h1>#Model</h1>
</div>
}
#using (Html.BeginForm("Create", "Home" /* route values */))
{
<input type="submit" value="Insert" />
}
#using (Html.BeginForm("Edit", "Home", new { id = 123 }))
{
<input type="submit" value="Update" />
}
2. And it's possible to pass message in the TempData:
public ActionResult Index(string message)
{
TempData["message"] = message;
return View((object)message);
}
In the view:
#{
var message = (TempData.ContainsKey("message") && TempData["message"] is string msg) ? msg : String.Empty;
ViewBag.Title = "Index Page";
}
#if (!String.IsNullOrEmpty(message))
{
<div class="jumbotron">
<h1>#Model</h1>
</div>
}
3. A message string might be included to the view model of the strongly typed view.

You can use toastr .... here is the example with detail
https://www.c-sharpcorner.com/UploadFile/97d5a6/toastr-notifications-to-your-web-site/

I like to use TempData to pass a message to a View. You can set the value of TempData right before the RedirectToAction:
TempData["message"] = "data inserted successfully";
return RedirectToAction("Index");
In the Index view, the message will only be displayed if TempData was set in the controller:
#if (TempData["message"] != null)
{
<div class="alert-info">#TempData["message"]</div>
}

Related

Cannot get the parameter from my textbox on the html

Hi im working right now on a page where you input the id of a person, and if its not in the system then it sends you to the Create , so you can register.
However
[HttpPost]
public ActionResult ingresarSolicitante(int? id)
doesn't get the id, even if I change it for a string and a textbox, I cannot get the value. Any ideas?
here is the html
#model Entrega02Programacion03.Models.Solicitante
#{
ViewBag.Title = "ingresarSolicitante";
}
<h2>ingresarSolicitante</h2>
<div>
#using (Html.BeginForm())
{
<p>
Buscar Solicitante por celuda: #Html.TextBox("Cedula")<br />
<input type="submit" value="Filtrar" />
</p>
}
</div>
and here is the code on the controller
[HttpPost]
public ActionResult ingresarSolicitante(string id)
{
// busco el solicitante
Solicitante solicitante = db.Solicitante.Find(id);
//si exite voy a crear expediente
if (solicitante != null)
{
TempData["solicitante"] = solicitante;
return RedirectToAction("InformeSolicitante");
}
// si no me redirije a crear solicitante
else
{
return RedirectToAction("Create");
}
}
// GET: Solicitantes/Edit/5
public ActionResult Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Solicitante solicitante = db.Solicitante.Find(id);
if (solicitante == null)
{
return HttpNotFound();
}
return View(solicitante);
}
I dont know whats wrong with the string id on this method that I allways get a null.
change textbox name #Html.TextBox("Cedula") to #Html.TextBox("id")
or change the parameter name of your action method to Cedula
Your Html Page is PageModelBase and you can get your Id from this. Or in other word put that id into the TextBox like:
#model Entrega02Programacion03.Models.Solicitante
#{
ViewBag.Title = "ingresarSolicitante";
}
<h2>ingresarSolicitante</h2>
<div>
#using (Html.BeginForm())
{
<p>
Buscar Solicitante por celuda: #Html.TextBox(Model.Id)<br />
<input type="submit" value="Filtrar" />
</p>
}
If you do this, you can set and get data from HTML and into HTML

Redirect back with message after file upload MVC 4 c#

I've working on MVC 4 application and want to redirect back with message to call action view:
Action that called : Upload
Current view : Index
public class HospitalController: Controller {
public ActionResult Index()
{
return View(Model);
}
[HttpPost]
public ActionResult Index(Model model)
{
return View(ohosDetailFinal);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Upload(HttpPostedFileBase upload,FormCollection form)
{
//Here i want to pass messge after file upload and redirect to index view with message
// return View(); not working
}
}
#using (Html.BeginForm("Upload", "Hospital", null, FormMethod.Post, new { enctype = "multipart/form-data", #class = "" }))
{
#Html.AntiForgeryToken()
#Html.ValidationSummary()
<input type="file" id="dataFile" name="upload" class="hidden" />
}
Thanks !
Follow the PRG pattern. After successful processing, redirect the user to another GET action.
You can return a RedirectResult using RedirectToAction method. This will return a 304 response to the browser with the new url in the location header and the browser will make a new GET request to that url.
[HttpPost]
public ActionResult Upload(HttpPostedFileBase upload,FormCollection form)
{
//to do : Upload
return RedirectToAction("Index","Hospital",new { msg="success"});
}
Now in the Index action, you may add this new parameter msg and check the value of this and show appropriate message. The redirect request will have a querystring with key msg (Ex :/Hospital/Index?msg=success)
public ActionResult Index(string msg="")
{
//to do : check value of msg and show message to user
ViewBag.Msg = msg=="success"?"Uploaded successfully":"";
return View();
}
and in the view
<p>#ViewBag.Msg</p>
If you do not prefer the querystring in the url, you may consider using TempData. But tempdata is available only for the next request.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Upload(HttpPostedFileBase upload,FormCollection form)
{
//Here i want to pass messge after file upload and redirect to index view with message
return Index();//or with model index
}
Try the below code, Hope It helps.!
View
#using (Html.BeginForm("Upload", "Hospital", null, FormMethod.Post, new { enctype = "multipart/form-data", #class = "" }))
{
if (TempData["Info"] != null)
{
#Html.Raw(TempData["Info"])
}
#Html.AntiForgeryToken()
#Html.ValidationSummary()
<input type="file" id="dataFile" name="upload" class="hidden" />
}
Controller
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Upload(HttpPostedFileBase upload,FormCollection form)
{
//Here i want to pass messge after file upload and redirect to index view with message
TempData["Info"]="File Uploaded Successfully!";
return RedirectToAction("Index");
}

Passing Data from one controller method to another in MVC

I have a page that has 2 text boxes First Name and last Name after user click on sign up button API will run and returns user info and shows another page(view) that had user Phone, email,.. That fill with the info that API returns. I have 1 controller and 2 views.
I get the info from API and return the second view but not sure how fill the text boxes with the info I have. The problem is using the models in view, I have 2 models one for each view. I am getting this error when I call the second view:
The model item passed into the dictionary is of type 'System.Collections.Generic.Dictionary`2[System.String,System.Object]', but this dictionary requires a model item of type Models.CreateLogInRequest'.
This is my controller:
[HttpGet]
public ActionResult SearchUser()
{
return View();
}
[HttpPost]
public async Task<ActionResult> SearchUser(UserSearchRequest userSearchRequest)
{
HttpClient client = new HttpClient();
object userObject = null;
string baseUrl = "http://test/api/users";
if (userSearchRequest.FirstName != null && userSearchRequest.LastName)
{
var response = await client.GetAsync(string.Format("{0}{1}/{2}/{3}", baseUrl, "/users", userSearchRequest.FirstName, userSearchRequest.LastName));
if (response.IsSuccessStatusCode)
{
userObject = new JavaScriptSerializer().DeserializeObject(response.Content.ReadAsStringAsync().Result) as object;
}
}
if (userObject != null)
{
return View("Create", userObject);
}
return View("Create", null);
}
[HttpPost]
public ActionResult Create(CreateLogInRequest createLogInRequest)
{
return View();
}
This is my First View that shows 2 text boxes:
#using (Html.BeginForm("SearchUser", "SignUp", FormMethod.Post))
{
#Html.AntiForgeryToken()
<input id="FirstName" name="FirstName" type="text" placeholder="First NAME" />
<input id="LastName" name="LastName" type="text" placeholder="LastName " />
<input id="btnSubmit" name="btnSubmit" type="submit" value="SIGN UP TODAY" />
}
and this is my model for 1st view:
public class UserSearchRequest
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
This is the second View:
#model Models.CreateLogInRequest
#{
ViewBag.Title = "Create";
}
#using (Html.BeginForm("create", "SignUp", FormMethod.Post))
{
#Html.AntiForgeryToken()
<input id="Email" name="Email" type="text" placeholder="Email" value="#Model.Email" />
<input id="Phone" name="Phone" type="text" placeholder="Phone" value="#Model.Phone" />
<input id="btnSubmit" name="btnSubmit" type="submit" value="CREATE ACCOUNT" />
}
and this is Model for this view:
public class CreateLogInRequest
{
public string Email { get; set; }
public string Phone { get; set; }
....
}
See my comments and try this:
[HttpGet]
public ActionResult SearchUser()
{
return View();
}
[HttpPost]
public async Task<ActionResult> SearchUser(UserSearchRequest userSearchRequest)
{
HttpClient client = new HttpClient();
CreateLogInRequest userObject = null;
string baseUrl = "http://test/api/users";
if (userSearchRequest.FirstName != null && userSearchRequest.LastName)
{
var response = await client.GetAsync(string.Format("{0}{1}/{2}/{3}", baseUrl, "/users", userSearchRequest.FirstName, userSearchRequest.LastName));
if (response.IsSuccessStatusCode)
{
userObject = new JavaScriptSerializer().DeserializeObject<CreateLogInRequest>(response.Content.ReadAsStringAsync().Result);
}
}
if (userObject != null)
{
return RedirectToAction("Create", userObject);
}
return View("Create", null);
}
[HttpPost]
public ActionResult Create(CreateLogInRequest createLogInRequest)
{
return View();
}
In the Controller you can create a new instance of Models.CreateLogInRequest model and fill the related properties received from 1st View. If Models.CreateLogInRequest does not contain such properties then it is better to load these values by using TempData or ViewBag in the Controller retrieved from the 1st View and pass them to the 2nd View. For the differences between ViewBag, ViewData, or TempData you might have a look at When to use ViewBag, ViewData, or TempData in ASP.NET MVC 3 applications. Hope this helps...

Mvc Model Error

I keep getting this error:
The model item passed into the dictionary is of type 'OutsourcedTicketPlatform.UI.ViewModels.Home.AccountSearchViewModel', but this dictionary requires a model item of type 'OutsourcedTicketPlatform.UI.ViewModels.Home.AccountDetailsViewModel'.
Home controller:
public class HomeController : Controller
{
[Authorize]
public ActionResult Index()
{
return View();
}
[Authorize]
public ActionResult SearchResults(AccountSearchViewModel model)
{
if (ModelState.IsValid)
{
AccountDetailsViewModel accountDetails = new AccountDetailsViewModel(model.CustomerReferenceNumber);
return View(accountDetails);
}
return View("Index");
}
[Authorize]
public ActionResult MobileResults(AccountDetailsViewModel model)
{
if (ModelState.IsValid)
{
AccountDetailsViewModel accountDetails = new AccountDetailsViewModel(model.CustomerReferenceNumber);
return View(accountDetails);
}
return View("Index");
}
}
MobileIssueReporterview:
#model OutsourcedTicketPlatform.UI.ViewModels.Home.AccountDetailsViewModel
#{
ViewBag.Title = "Mobile Issue Reporter";
}
<h2>Mobile Issue Reporter</h2>
<p>Hi (CustomerName) are you phoning today to log the mobile device as lost or stolen?</p>
<p>"Please Confirm your mobile number"</p>
<p>#Html.TextBox("mobileNumber")</p>
Search results view (this navigates to the mobile issue reporter)
#model OutsourcedTicketPlatform.UI.ViewModels.Home.AccountDetailsViewModel
#{
ViewBag.Title = "Key Account Management";
}
<fieldset>
<legend>#ViewBag.Title</legend>
<p>Please provide the account name:</p>
#foreach (var item in Model.AccountContacts)
{
#Html.RadioButton("AccountContact", item) #item
}
<input id="ContactNotListedButton" type="button" value="Contact name not on list" />
<p>Please provide the first line of the billing address:</p>
#Html.RadioButton("BillingAddressFirstLine", Model.BillingAddressFirstLine, false) #Model.BillingAddressFirstLine
<input id="NoMatchingDetailsButton" type="button" value="No Matching Details" />
#* 1 = Unicom, 2 = Titan *#
#if (Model.AccountType == 1 || Model.AccountType == 2)
{
<input id="NextButton" type="button" value="Next" />
}
#if (Model.AccountType == 1 && Model.IsKeyAccount && Model.HasActiveMobileContracts)
{
using (Html.BeginForm("MobileResults", "Home", FormMethod.Post))
{
#Html.Hidden("CustomerReferenceNumber","123456")
#Html.Hidden("customerName", "John Smith")
#Html.Hidden("mobileNumber", "123456789")
<input type="submit" value="Mobile Lost or Stolen?" />
}
}
</fieldset>
The error is happening when I click on the Mobile Lost or Stolen? button
It Seems You are passing populated values with the model AccountSearchViewModel but that view is expecting data from AccountDetailsViewModel chek with AccountDetailsViewModel model it will work fine.

passing input text from view to contoller with FacebookContext using Facebook app

I am trying to pass a input text from view to controller in Facebook birthday app:
link for app: http://www.asp.net/mvc/tutorials/mvc-4/aspnet-mvc-facebook-birthday-app
in HomeController
[FacebookAuthorize("email", "user_photos")]
public async Task<ActionResult> Index(FacebookContext context)
{
if (ModelState.IsValid)
{
var user = await context.Client.GetCurrentUserAsync<MyAppUser>();
return View(user);
}
return View("Error");
}
[HttpPost]
[FacebookAuthorize("email", "user_photos")]
public async Task<ActionResult> Index(string txt,FacebookContext context)
{
if (ModelState.IsValid)
{
var user = await context.Client.GetCurrentUserAsync<MyAppUser>();
// my code , I use txt here
return View(user);
}
return View("Error");
}
view:
#using facebookpostc.Models
#using Microsoft.AspNet.Mvc.Facebook.Models
#using Microsoft.AspNet.Mvc.Facebook
#model MyAppUser
#{
ViewBag.Title = "Home Page";
}
<article id="content">
<div class="right">
#using (Html.BeginForm("Index", "HomeController"))
{
<br />
<span>please input your text: </span>
<input type="text" id="txt" name="txt" />
<input type="submit" />
}
</div>
</article>
but it is not passing text, I tried to pass text in many way but none of them passed text.
You can read it from FormCollection:
[HttpPost]
[FacebookAuthorize("email", "user_photos")]
public async Task<ActionResult> Index(FormCollection form,FacebookContext context)
{
if (ModelState.IsValid)
{
string temp = form["txt"].ToString();
var user = await context.Client.GetCurrentUserAsync<MyAppUser>();
// my code , I use txt here
return View(user);
}
return View("Error");
}

Categories

Resources