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

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

Related

Show message for insert and update data in index view page

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>
}

asp.net mvc submit doesnt hit actionresult method

would you mind to help me and say what I am doing wrong? I cannot spot the error and consequently after clicking the submit button, the HttpPost ActionResult method is not being hit?
Controller
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult Index(testModel model)
{
if (ModelState.IsValid == true)
{
using (testRepository repository = new testRepository())
{
}
}
return View();
}
And the View
#using (Html.BeginForm("Index", "Test", FormMethod.Post, new {autocomplete="off" }))
{
<fieldset>
#Html.LabelFor(m => m.testValue)
#Html.TextBoxFor(m => m.testValue)
<input type="submit" value="Submit" />
</fieldset>
}

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...

Sending a phrase (variable) from searcher (from view) to controller, asp.net mvc

I'm trying to create searcher in asp.net. I'm so green about it. I'm trying to create in view and send to controller variable, which has text written in searcher. In that moment, I have smth like that -->
My question is, where and how create and send variable and give her data written in searcher?
Layout
form class="navbar-form navbar-left" role="search">
#using (Html.BeginForm("Index", "Searcher", FormMethod.Post, new { phrase = "abc" }))
{
<div class="form-group">
<input type="text" class="form-control" placeholder="Wpisz frazę...">
</div>
<button type="submit" class="btn btn-default">#Html.ActionLink("Szukaj", "Index", "Searcher")</button>
}
</form>
Controller
public class SearcherController : ApplicationController
{
[HttpGet]
public ActionResult Index(string message)
{
ViewBag.phrase = message;
getCurrentUser();
return View();
}
}
View
#{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<ul>
<li>#ViewBag.message</li>
</ul>
You're missing a key part of MVC -> the Model.
Let's create one first:
public class SearchModel
{
public string Criteria { get; set; }
}
Then let's update your "Layout" view (don't know why you had a form in a form?):
#model SearchModel
#using (Html.BeginForm("Index", "Searcher", FormMethod.Post, new { phrase = "abc" }))
{
<div class="form-group">
#Html.EditorFor(m => m.Criteria)
</div>
<button type="submit" class="btn btn-default">#Html.ActionLink("Szukaj", "Index", "Searcher")</button>
}
Then your action that serves that view:
[HttpGet]
public ActionResult Index()
{
return View(new SearchModel());
}
Then your post method would be:
[HttpPost]
public ActionResult Index(SearchModel model)
{
ViewBag.phrase = model.Criteria;
getCurrentUser();
return View();
}

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.

Categories

Resources