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
Related
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>
}
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...
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();
}
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.
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