TempData Message in different tab - c#

i want in my page after an action like RegisterUser give a message to client for result.so i use TempData(becase i use RedirectToAction method i cant use viewbag).my problem is that if user open another tab in same time message will show in another tab(any page it can be).how can i solve that??
#using (#Html.BeginForm("RegisterUser", "UserManagement", FormMethod.Post))
{
#Html.AntiForgeryToken()
#Html.Partial("_RegisterPagesMessage")
<table class="Registertbl">
<tr>
<td>نام*</td>
<td> #Html.TextBoxFor(m => m.FName, new { maxlength = 20})<br />
</td>
<td>سمت*</td>
<td>#Html.TextBoxFor(m => m.Post, new { maxlength = 200})</td>
</tr>
</table>
<br />
<input type="submit" value="Insert" class="insertBtn" />
#Html.ActionLink("back", "ViewUserList", "UserManagement")
}
//_RegisterPagesMessage
#if (TempData["MessageResult"] == null)
{
<div id="ErrorContent" class="msg-Red" style="display: none;"></div> <br />
}
else
{
<div id="ErrorContent" class="#TempData["cssClass"]" >
#Html.Label(TempData["MessageResult"] as string)
</div> <br />
}
//Controller
[HttpGet]
public ActionResult RegisterUser()
{
return View(new User());
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult RegisterUser(Common.UsersManagement.Entities.User model)
{
SetUserManagement();
var Result = userManagement.RegisterUser(model);
SetMessage(Result.Mode.ToString());
if (Result.Mode == Common.Extensions.ActionResultMode.Successfully)
{
return RedirectToAction("RegisterUser");
}
// if not Successfull
return View(model);
}
protected void SetMessage(string Mode)
{
var messageResult = XmlReader.FindMessagekey(Mode);
TempData["MessageResult"] = messageResult.MessageContent;
TempData["cssClass"] = messageResult.cssClass;
}

Easy solution. In your RegisterUser controller method check for a value in TempData and transfer it to ViewData, then have the View check the ViewData, which only survives for that one view.
[HttpGet]
public ActionResult RegisterUser()
{
if( TempData.ContainsKey( "MessageResult" )
{
ViewData["MessageResult"] = TempData["MessageResult"];
ViewData["cssClass"] = messageResult.cssClass;
}
return View(new User());
}
Now in the view use ViewData instead of TempData.

Related

How get value from current controller?

if I call the POST action method I want to get the data from the files-object of my GET action method.
public class UploadController:Controller {
public IActionResult Index(){
// Here is some code
return View(files);
}
[HttpPost]
public IActionResult Index(IFormFile importFile){
{
// Here I want to work with data from the files object of my Index() method above
return View("Index", newFiles);
}
}
My View looks like this:
#using MVC-project.Models
#model UploadViewModel
<table>
<tr>
<th>File Name</th>
<th></th>
</tr>
#foreach (string file in Model.FileName )
{
<tr>
<td>#file</td>
<td>#Html.ActionLink("Download", "DownloadFile", new { fileName = file })</td>
</tr>
}
</table>
#using (Html.BeginForm("Index", "Upload", FormMethod.Post, new { #id = "upldFrm", #enctype = "multipart/form-data" }))
{
<div class="row">
<div class="form-group col-md-6">
<input type="file" class=" form-control" name="importFile" />
</div>
<div class="form-group col-md-6">
<input type="submit" name="filesubmit" value="Upload" />
</div>
</div>
}
// Here is some code and if-case for processing after the POST submit
How can I use the data from the files object of my GET Index() action method in my POST Index method?
There are a number of ways to do this. You could put the files in a view data dictionary in the get controller.
ViewData["Files"] = files
Then retrieve it from your post.
var files = ViewData["Files"]
You could also pass the files to a view model in your get controller, send it to your view. Then pass it to the post action when you submit the form on the view.
public class ViewModel {
public string Files {get; set;}
public IFormFile File {get; set;}
}
[HttpGet]
public IActionResult Index(){
var viewModel = new ViewModel
{
Files = files
};
return View(viewModel);
}
[HttpPost]
public IActionResult Index(ViewModel viewModel){
....
}
Here is the example to get the data before the post action.
public ActionResult Edit(int id)
{
HttpResponseMessage response =GlobalVariables.webApiClient.GetAsync("Tbl_Books/"+ id.ToString()).Result;
return View(response.Content.ReadAsAsync<Books>().Result);
}
[HttpPost]
public ActionResult Edit(Books newbook)
{
HttpResponseMessage response =GlobalVariables.webApiClient.PostAsJsonAsync("Tbl_Books", newbook).Result;
HttpResponseMessage response =
GlobalVariables.webApiClient.PutAsJsonAsync("Tbl_Books/" + newbook.BookId, newbook).Result;
return RedirectToAction("Index");
}
Here I will get the data from my get API method and this data is passed to the post view[HttpPost] and then post or put action can be performed.

How to change data in a table with a button click

I would like to have a button where on click it changes a string value from null to any other text (for example 'yes'). I have a button in the view that calls an update method in the controller but I don't know what to put inside that update method.
In the view, this is the button ('item' refers to model, 'Activated' refers to a string column in that model which has a default value of null)
#model IEnumerable<ProjectMVC2.Models.ApplicationUser>
#foreach (var item in Model)
{
#if (item.Activated == null)
{
using (Html.BeginForm("Update", "User", new { id = item.Id })){
#Html.AntiForgeryToken()
<td class="button btn-default" align="center">
<input type="submit" value="Activate" class="btn btn-default" />
</td>
}
}
else if (item.Activated == "Yes")
{
<td class="c" align="center">
Activated already
</td>
}
I have the method in my controller
public class UserController : BaseController
{
ApplicationDbContext context;
public UserController()
{
context = new ApplicationDbContext();
}
// GET: User
public ActionResult Index()
{
var User = context.Users.ToList();
return View(User);
}
public ActionResult Update()
{
return RedirectToAction("Index")
}
}
In the method what should I put that will allow for the change to happen? Please if anyone can help, I will really appreciate it.
You'll have to updated your model itself:
public ActionResult Update()
{
var users = context.Users.ToList();
foreach(var user in users)
{
user.Activated = "Yes";
}
context.SaveChanges();
return RedirectToAction("Index")
}
However, this changes are persisted so if you come back to the page again you'll still see user.Activated = "Yes". If you need something temporary, I would suggest to use following code.
public ActionResult Update()
{
var users = context.Users.ToList();
foreach(var user in users)
{
user.Activated = "Yes";
}
return View("Index", users);
}
Use a for loop to take advantage of model binding to a collection.
This is accomplished by using an indexing expression e.g. Model[i].
Add a HiddenFor to tell the controller which users need to be activated.
#for (var i = 0; i < Model.Length; i++)
{
var item = Model[i];
#if (item.Activated == null)
{
using (Html.BeginForm("Update", "User", new { id = item.Id }))
{
#Html.AntiForgeryToken()
#Html.HiddenFor(_ => Model[i].Id)
<td class="button btn-default" align="center">
<input type="submit" value="Activate" class="btn btn-default" />
</td>
}
}
else if (item.Activated == "Yes")
{
<td class="c" align="center">
Activated already
</td>
}
The update method now accepts a collection of users to activate.
public ActionResult Update(IEnumerable<ApplicationUser> usersToActivate)
{
// Are there any user to active?
if (usersToActivate == null)
{
return View();
}
var userIds = usersToActivate.Select(u => u.Id).ToList();
var usersToUpdate = context.Users.Where(user => userIds.Contains(user.Id));
foreach (var userToUpdate in usersToUpdate)
{
userToUpdate.activated = "Yes";
}
context.SaveChanges();
return RedirectToAction("Index")
}

How to update the model data changed inside the view

I have a list of categories that I want to edit. I can successfully pass them into the controller.
public ActionResult Edit()
{
if (!IsAdmin) return RedirectToAction("Index", "Home");
ViewBag.IsAdmin = IsAdmin;
var categories = _model.Categories.ToList();
return View(categories);
}
Then I have a view to edit the names of the categories.
#using MyStructures.Models
#model List<MyStructures.Models.Category>
#using (Html.BeginForm("Update", "Categories", FormMethod.Post))
{
foreach (var category in Model)
{
var categoryToEdit = #category;
<table>
<tr>
<td>Category Number: #category.Id</td>
<td>#Html.EditorFor(x => categoryToEdit.Name)</td>
<td colspan="2">
<input type="submit" value="Save"
formaction=#Href("~/Categories/Update/") />
</td>
</tr>
</table>
}
<input type="submit" value="Cancel"
formaction=#Href("~/Home/Index/") />
}
How do I pass the updated value to the "Update" controller? The value of Category obj is null.
[HttpPost]
public ActionResult Update(Category obj)
{
var existing = _model.Categories.Find(obj.Id);
existing.Name = obj.Name;
_model.SaveChanges();
return RedirectToAction("Index", "Home");
}

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.

Not able to run another function for another button inside same view

I have got the two buttons in the same view one is working with the data to show in a label in another view and I have written the function for the button2 (adding another value), when I click on the button2 its not showing the data in view ..... rather it's giving error like this ... http:404 Resource not found error
and this is the view
#model MvcSampleApplication.Models.products
#{
ViewBag.Title = "Valuesadd";
}
<h2>Valuesadd</h2>
#using (Html.BeginForm("SubmitValue","EnterValue",FormMethod.Post))
{
<div>
<fieldset>
<legend>Enter Textbox Value</legend>
<div class ="editor-label">
#Html.LabelFor(m => m.EnteredValue)
</div>
<div class="editor-field">
#Html.TextBoxFor(m=>m.EnteredValue)
</div>
<p>
<input type="submit" value="Submit1" />
</p>
</fieldset>
</div>
}
#using (Html.BeginForm("SubmitValue2","EnterValue",FormMethod.Post))
{
<p>
<input type="submit" value="Submit2" />
</p>
}
and this is the controller for
namespace MvcSampleApplication.Controllers
{
public class EnterValueController : Controller
{
[HttpPost]
public ActionResult SubmitValue(MvcSampleApplication.Models.products model)
{
TempData["logindata"] = model.EnteredValue;
return RedirectToAction("submittedvalues" , "SubmitValue2");
// how can we redirect to another view when the button is clicked in one view
}
public ActionResult submittedvalues()
{
var model = new MvcSampleApplication.Models.category();
string data = TempData["logindata"] != null ? TempData["logindata"].ToString() : "";
model.lablvalue = data;
return View(model);
}
// action for second button click
public ActionResult submittedvalues2()
{
var model = new MvcSampleApplication.Models.category();
string data = TempData["logindata"] != null ? TempData["logindata"].ToString() : "";
model.lablvalue = "HIIII"+data;
return View(model);
}
}
}
would you pls suggest any idea ..
Many thanks...
Your form action and action in the controller are not named the same. Also you don't have a HttpPostfor it
#using (Html.BeginForm("SubmitValue2","EnterValue",FormMethod.Post))
{
}
//add this
[HttpPost]
public ActionResult submittedvalues2()
{
var model = SOMETHING;
return View("submittedvalues", model);
}
or
[HttpPost]
public ActionResult submittedvalues2()
{
//Do your post actions and redirect to action
return RedirectToAction("submittedvalues");
}
SubmitValue2 in the form should be submittedvalues2, and add a HttpPost attribute on it

Categories

Resources