how to pass data from view to controller - asp.net-mvc

I am new to asp.net MVC5 and i am trying to pass data from view to controller as a string.
Here is controller class:
namespace Movies.Controllers
{
public class HelloWorldController : Controller
{
// GET: HelloWorld
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult welcome(FormCollection fc, string reportName)
{
ViewBag.Message = reportName;
return View();
}
}
}
Here is Index View:
#{
ViewBag.Title = "MVC Movies";
}
<h2>My Movies List</h2>
<p>Hellow from our view template</p>
#using (Html.BeginForm("Welcome", "HelloWorld", FormMethod.Get))
{
<p>
<input type="text" name="reportName" />
<input type="submit" />
</p>
}
Here is welcome view:
#{
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>welcome</h2>
#{
ViewBag.Title = "Welcome";
}
<ul>
#for (int i = 0; i < 2; i++)
{
<li>#ViewBag.Message</li>
}
</ul>
Actually my Index method is passing a view that will have a textbox for string in it in a form and then on clicking submit button application should pass that string in the Welcome method in the same controller. On clicking submit button browser is showing a windows that resources con't be found.
Whats the problem..? thank you for your time..:)

1) The action name is case sensitive, you are using "Welcome" in the form definition , but the action must has the name "welcome" with w lower case.
2) Your form is doing a GET but you are specting a POST in the action
[HttpGet]
public ActionResult welcome(FormCollection fc, string reportName)
{
ViewBag.Message = reportName;
return View();
}

Replace FormMethod.Get with FormMethod.Post in your beginform.

Modify FormMethod.Get to FormMethod.Post:
#using (Html.BeginForm("Welcome", "HelloWorld", FormMethod.Post))
{
<p>
<input type="text" name="reportName" />
<input type="submit" />
</p>
}
Change your action implementation to this:
[HttpPost]
public ActionResult welcome(FormCollection fc)
{
ViewBag.Message = fc["reportName"];
return View();
}
However, I'd strongly suggest that you create a view model for your form and use it instead of FormCollection.

Related

Update a field in view based on the model in ASP.NET MVC

I need to do a calculator in ASP.NET MVC.
For the beginning I want to receive the value from the input field in controller and prefix it with the string "123". At the end I will process the expresion received and return the result.
I have the following model:
namespace CalculatorCloud.Models {
public class Calculator
{
public string nr { get; set; }
} }
In the view I am using the model:
#model CalculatorCloud.Models.Calculator
#{
ViewBag.Title = "Calculator";
}
#using (Html.BeginForm("Index", "Home"))
{
<div>
<div class="header">
#Html.TextBoxFor(m => m.nr, new { #id = "nr"})
<input type="button" id="C" name="C" value="C" />
<input type="button" id="back" name="back" value="<-" />
[...]
<div class="sum">
<input type="submit" value="=" />
</div>
</div>
}
The controller is like this:
namespace CalculatorCloud.Controllers
{
public class HomeController : Controller
{
Calculator model = new Calculator();
public ActionResult Index(string nr)
{
model.nr = "123" + nr;
return View(model);
}
}
}
I have the following problem: when pressing on submit button I am expecting to be displayed on the textbox the value from that was previously in the textbox, prefixed with the string "123".
But now it is kept the value from the textbox without the string "123".
Can someone help me with this?
Thank you! :)
If you want to modify the value of a model property in a postback action you will need to remove it from the ModelState:
public ActionResult Index(string nr)
{
ModelState.Remove("nr");
model.nr = "123" + nr;
return View(model);
}
The reason for this is that Html helpers such as TextBoxFor will first look at the value present in the ModelState and then in your view model property when rendering the value. This is by design.

How to check each form controller's type posted to action method?

View:
#using (Html.BeginForm())
{
#Html.Label("WebLinkLabel")
#Html.Editor("WebLinkTextbox")
#Html.Label("WebEnabledLabel")
#Html.CheckBox("WebEnabledCheckbox")
<input name="Save" type="submit" value="Save" />
}
Action Method:
[HttpPost]
public ActionResult Index(FormCollection collection)
{
foreach (var key in collection.AllKeys)
{
var typee = collection.GetType();
}
return View();
}
GetType() gives me that:
collection.AllKeys.GetType()
{Name = "String[]" FullName = "System.String[]"} System.Type {System.RuntimeType}
I would like to know like the first controller is of type Textbox, another one is Checkbox etc..

Wiring partial view to model

I'm in a bit of a rut with MVC3 partial views. What I'm trying to do is have a partial view within one of my pages, and have that data from the partial view stored in the model that gets passed back into the main view. Though, what's happening right now is that after submitting the data, the model returned back to the controller has the partial view model set as null.
Model
public class MyModel {
...(other variables)...
[Required]
[NotMapped]
public virtual MyPartialView myPartial { get; set; }
}
View
#model MvcPartialViewExample.Models.MyModel
#{
ViewBag.Title = "Create";
}
#using (Html.BeginForm()) {
#Html.ValidationSummary(true)
<fieldset>
...(other data)...
#{
Html.RenderPartial("_MyPartialView", Model.MyPartialView, new ViewDataDictionary());
}
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
Controller
public class MyModelController : Controller
{
private MyModelContext db = new MyModelContext();
//
// GET: /PartialViewTesting/Create
public ActionResult Create()
{
return View(new MyModel());
}
If you want to pass the Model.MyPartialView object back to the controller, then you need to add another Action method to the controller. Should look something like this:
[HttpPost]
public ActionResult Create(MyPartialView model)
{
// handle postback here
}

ASP.NET MVC 3 - two forms, two ActionResult but one Controller?

I have a new asp.net mvc 3 project with following structure:
Views:
/Home/Index.cshtml
#{
Html.BeginForm("Index", "Home", "POST");
}
<input id="name" type="text" />
<input id="submit_1" type="submit" value="submit" />
#{
Html.EndForm();
}
#{
Html.BeginForm("FindTeacher", "Home", "POST");
}
<input id="name" type="text" />
<input id="submit_2" type="submit" value="submit" />
#{
Html.EndForm();
}
Controller:
/Controllers/HomeController.cs
public class HomeController : Controller
{
[HttpPost]
public ActionResult Index(string name)
{
//call the model FindStudent() and set the ViewData
return View();
}
[HttpPost]
public ActionResult FindTeacher(string name)
{
//Call the FindTeacher () and set the ViewData
return View();
}
}
The submit_1 is works, because it found the ActionResult of Index, however, when i click submit_2, it say cannot find FindTeacher Controller.
So how can i do?
Try this
[HttpPost]
public ActionResult FindTeacher(string name)
{
// do updates
return RedirectToAction("Index"); or
return Index();
}
"POST" is wrong; it should be FormMethods.Post.
Because of that, your forms are actually submitting GET requests.
Index works because you have a different action that responds to GET requests to /Index.
FindTeacher fails because there is no GET for that action.

Why is my ASP.NET MVC Edit Form not retaining data?

On my edit view, the information doesn't seem to be displayed on the form in the textboxes. Any idea why this is happening? Any help would be greatly appreciated.
Here's how my edit functions inside the controller look like:
[HttpGet]
[Authorize(Roles = "Admin")]
public ActionResult Edit(int id)
{
var logic = new ContactBUS();
var user = logic.GetContact(id);
var mUser = Membership.GetUser(user.Username);
bool memUserExists = doesUserExist(mUser);
if (memUserExists)
{
var model = new RoleListViewModel
{
AllRoles = Roles.GetAllRoles().ToList()
};
return View(model);
}
return View(logic.GetContact(id));
}
[HttpPost]
[Authorize(Roles = "Admin")]
public ActionResult Edit(Contact contact)
{
var logic = new ContactBUS();
if (ModelState.IsValid)
{
logic.EditContact(contact);
return RedirectToAction("List");
}
else
return View(contact);
}
}
Edit.cshtml:
#model ContactWeb.Models.RoleListViewModel
<h2>Edit</h2>
<div style="float:left;width:350px;">
#{Html.RenderPartial("Form", new ContactWebLibrary.Contact());}
</div>
and Form.cshtml:
#model ContactWebLibrary.Contact
#using (Html.BeginForm()) {
<input type="hidden" value="#Model.Id" />
<fieldset id="ContactEditor">
<legend>Fields</legend>
<div>
#Html.LabelFor(c=>c.FirstName, "First Name")
#Html.TextBoxFor(c=>c.FirstName)
#Html.ValidationMessageFor(c=>c.FirstName)
</div>
<div>
#Html.LabelFor(c=>c.LastName, "Last Name")
#Html.TextBoxFor(c=>c.LastName)
#Html.ValidationMessageFor(c=>c.LastName)
</div>
...
<input type="submit" value="#(Model.Id == 0 ? "Create" : "Edit" )" />
</fieldset>
}
If memUserExists is true then a new RolesListViewModel is passed to the Edit view. This in turn passes a brand new Contact model to the partial view each time this partial view is rendered:
#{Html.RenderPartial("Form", new ContactWebLibrary.Contact());}
So the contact used in the partial will not contain any information to display, hence, no values are being displayed.
Does logic.GetContact(id) return a RoleListViewModel? Otherwise, when memUserExists is false, I don't think the following line would work when returning the Edit view:
return View(logic.GetContact(id));
And also, the following line in your [HttpPost]:
return View(contact);
This passes a Contact object to a view that is expecting a RoleListViewModel.
Hope this helps.

Resources