MVC4 Pass Model from View to Controller - forms

//Model
public class Car
{
string name{get;set;}
double speed {get;set;}
//etc.
}
Basic model
//Controller
public ActionResult ModifyCar(Car c)
{
c = GetAdditionalData(c.name, c.speed);
return View(c);
}
So I'm making call to outside service to get additional data for car.
Below is the form which I'm really confused on. I am just going to write this in HTML.
But from here I'd like to take a basic empty model.. populate it then send to the controller for additional data.
//View
#model Car
<form id="carform" method="post" action="/Car/ModifyCar"> //Guessing
<input id="carName" /> //Somehow bind with #model.name
<input id="carSpeed" /> //Somehow bind with #model.speed
<input type="submit" /> //Somehow send the model to the controller
</form>
Sorry I'm not really good at the View part at all but I hope you can see where I was going here.
Also, I'm doing validation that requires a form id.. I noticed that there is no form id when using HTML Helper to make the form. Thats going to break my CSS I wrote.
Any help would be greatly appreciated.
Thanks

Try this :
#model Car
<form id="carform" method="post" action="/Car/ModifyCar"> //Guessing
<input id="carName" name="carName" value=#Model.name /> //Somehow bind with #model.name
<input id="carSpeed" name="carSpeed" value=#Model.speed /> //Somehow bind with #model.speed
<input type="submit" value="Submit" /> //Somehow send the model to the controller
</form>
when your form will submit it will go to ModifyCar action in Car
Controller.
But as you has mentioned in your question that we cannot give id in html helper ,it is wrong we can for ex:
#using(Html.BeginForm("ModifyCar","Car",FormMethod.Post,new{ id="carform" }))
the above BeginForm() will render same html as:
<form id="carform" method="post" action="/Car/ModifyCar">

Related

Checkbox input remains false on form submit

I am trying to post a form and even though all the inputs map their value accordingly in the receiving controller-method , the bool-s of checkbox-es remain false.
What am i doing wrong ?
POCO
class MyPoco
{
public string User{get;set;}
public bool Require {get;set;}
}
Form
<form id="createForm" method="post" action="[some url]">
<input type="checkbox" id="require" name="Require" />
<input type="text" id="user" name="User"/>
</form>
Controller (method)
[HttpPost]
[Route("[some url]")]
public async Task<long> CreateAsync(MyPoco request)
{
}
Why in my case above does request.Require is always false.I have mapped them correctly (the name attribute).
The reason is that you forget to set value of checkbox:
<input type="checkbox" id="require" name="Require" value="true" />
If a checkbox is checked, then the postback values will contain a key-value pair of the form [InputName]=[InputValue]
If a checkbox is not checked, then the posted form contains no reference to the checkbox at all.
I see you are missing asp-for attribute for your checkbox input. Instead of name="Require", use asp-for="Require" as follows:
#model MyPoco
<input asp-for="Require" type="checkbox" id="require" />
If you don't want to use asp-for attribute then you have to use jQuery as follows:
$(document).on('change','#require',function() {
if ($(this).is(':checked')) {
$(this).val(true)
} else {
$(this).val(false)
}
});

MVC how can i post a form without using a model

I would like to know how i could sumbit a form in mvc 4 without using a model binding to the view.
can some one please demontrate how? and how can i use that form in the controller?
It is very easy to use a form without any sort of Model binding.
Simple set up your for using either #using(Html.BeginForm()){ ... } or plain html.
<form id="myForm" action="/ControllerName/ActionName" method="Post">
<input type="text" name="foo" value="FOOOO" />
<input type="text" name="bar" value="Baaaar" />
<button type="submit">Submit</button>
</form>
When you post this to the ActionResult, your action result just needs to be set up to accept a string value named foo and one named bar
[HttpPost]
public ActionResult ActionName(string foo, string bar){
// your code here
return View();
}

how pass form from module to component in joomla 3.1

I wana create a front-end joomla component and this is my first experience.
here is important things:
1-component/controller.php
class TestController extends JControllerLegacy
{
public function display($cachable = false, $urlparams = false)
{
$view= JFactory::getApplication()->input->getCmd('view','items');
JFactory::getApplication()->input->set('view', $view);
parent::display($cachable, $urlparams);
}
}
2: com_test/model/items.php
<?php
defined('_JEXEC') or die();
jimport( 'joomla.application.component.modellist' );
class TestModelItems extends JModelList
{
public function __construct($config = array())
{
if (empty($config['filter_fields']))
$config['filter_fields'] = array('id', 'title', 'catid');
parent::__construct($config);
}
function getListQuery()
{
$db = JFactory::getDBO();
$query = $db->getQuery(true);
$query->select(...)
return $query;
}
}
I can print the query result on default.php on view folder!
but I wana another thing.
I have a form like this in the front page of my site in a custom module:
<form action="" method="post">
<input type="text" name="wordsearch" value="search">
.
.
<input type="submit" />
</form>
Now!
I do not know how can I send this form (with post method) to getListQuery() function in model folder...how can do it?
i wana when sb click submit form, the component filter query sql according to values of form and then show new result to user!
i googled for hourse but no chance to solve. thanks for your help.
You can submit Form from module to component as follows.
Suppose your component name is com_helloworld The in your module form should have the following things.
<form action="" method="post">
<input type="text" name="wordsearch" value="search">
.
.
<input type="hidden" name="option" value="com_helloworld" />
<input type="hidden" name="view" value="yourview" />
<input type="hidden" name="task" value="my_controller_fun" />
<input type="hidden" value="your_controller_file_name" name="controller">
<input type="submit" />
</form>
In this example your controller file should have my_controller_fun method from controller to model you can use regular method. This methods will get all the form data in your controller , then you can pass that to model.
Detailed :
In your controller file.
function my_controller_fun(){
$post_array = $_POST;
$model = $this->getModel('Profile', 'UsersModel');//example for including profile model you can specify your model file name
$model->function_inyourmodel($post_array);//this function should be in model
}
Hope its help..

Dynamically adding form elements with jQuery and Zend_Form

I have a form in which people shall be able to add the same portion of elements with a plus-button, so that something like this is produced:
<div id="person-1" class="person">
<input type="text" name="name-1" id="name-1" />
<input type="text" name="age-1" id="age-1" />
</div>
<!-- as of here, it's JS created -->
<div id="person-2" class="person">
<input type="text" name="name-2" id="name-2" />
<input type="text" name="age-2" id="age-2" />
</div>
<div id="person-3" class="person">
<input type="text" name="name-3" id="name-3" />
<input type="text" name="age-3" id="age-3" />
</div>
I already managed to write jquery-code that allows me to add the same elements once again with a new id (name-1, age-1, name-2, age-2, name-3, age-3, …).
Of course, Zend_Form does not know about name-2 and name-3, so it just drops them when the form contains an error and is displayed again. Neither can I access the value of name-2 with $form->getValue('name-2'). I have to go over raw $this->getRequest()->getPost().
Is there a better method I can use to combine Zend_Form and javascript-based added form elements (of same type like an hardcoded element).
Caveat: In the real problem, it’s select and not input. Found out this could make a difference (with ->setIsArray(true)), but using select would blow up the example code.
What you could do is create a subform container inside your main form and add an X amount of subforms to that container.
For example:
class My_Form extends Zend_Form
{
private $_numPersons = 1;
public function setNumPersons($numPersons)
{
$this->_numPersons = (int) $numPersons;
}
public function init()
{
$container = new Zend_Form_SubForm();
$this->addSubForm($container, 'persons');
for($index = 0; $index < $this->_numPersons; $index++) {
$personForm = new My_PersonForm();
$container->addSubForm($personForm, $index+1);
}
}
}
When rendered, the input fields will have names like persons[1][name]. Note the $index+1, Zend_Form does not allow a form to be named '0'.
Ofcourse, you should only use this method if the amount of person subforms is limited.
Another strategy would be to override the isValid method and use a single My_PersonForm form to validate all the person data.
Sidenote; the above code will only work when you define the numPersons as part of the options set, when creating the form instance. E.g.;
$form = new My_Form(array('numPersons' => 10));

ASP .Net MVC 2 custom Helper Grid not posting Model to controller action

I've created a custom helper that renders a grid and receives the strongly typed view's model as a parameter.
Basically my view looks like this:
<% using (Html.BeginForm("UpdateValues", "Home", FormMethod.Post)) { %>
<%= Html.MyGrid(Model)%>
<input type="submit" value="Update Values" />
<%} %>
But when I click on the submit button, all the values on the model are null.
This is what the controller looks like:
[HttpPost]
public string UpdateValues(AssignmentResultsVm assignmentResults)
{
//..... do something
}
How can I make this work?
Thanks in advance.
You need to make sure that the items are arranged in your grid so that the default model binder can map the data map to your view model class.
This is done by index the name property of the data your are binding like this:
<form method="post" action="/Home/Create">
<input type="text" name="[0].Title" value="Curious George" />
<input type="text" name="[0].Author" value="H.A. Rey" />
<input type="text" name="[1].Title" value="Code Complete" />
<input type="text" name="[1].Author" value="Steve McConnell" />
<input type="submit" />
</form>
You can have this done for you by the EditorTemplates feature of asp.net mvc which is exemplified in this article.