passing value from view to controller in MVC - asp.net-mvc

This is my view
<form method="post" action="/LoadCustomerAndDisplay/Search">
<fieldset>
<legend>Customer Book</legend>
<%= Html.Label("Name") %>
<%: Html.TextBox("Name") %>
<br />
<br />
<div>
<input type="submit" value="Sign" />
</div>
</fieldset>
</form>
This is my controller...
public ActionResult Search()
{
CustomerModels objCustomer = new CustomerModels();
var dataval = objCustomer.getData();
return View(dataval);
}
How can i get the value of Name textbox in the controller and pass it to the the getData like this....
var dataval = objCustomer.getData(ViewData['Name']);
this i put...showing error on fname....missing adding directive....what's the issue now...
<% Html.BeginForm("Search", "LoadCustomerAndDisplay");%>
<%: Html.TextBoxFor(m => m.fname) %>
<p>
<button type="submit">
Save</button></p>
<% Html.EndForm();%>

Use strongly typed view. In your GET action method, pass an object of your ViewModel to the view and use the HTML helper methods to create the input elements. When you submit the form, due to MVC model binding, you will get the values as the property values of the ViewModel in the POST action method.
Your GET action can stay same
public ActionResult Search()
{
CustomerModels objCustomer = new CustomerModels();
var dataval = objCustomer.getData();
// Assuming this method returns the CustomerViewModel object
//and we will pass that to the view.
return View(dataval);
}
so your View will be like
#model CustomerViewModel
#using (Html.BeginForm())
{
#Html.LabelFor(x=>x.Name)
#Html.TextBoxFor(x=>x.Name)
<input type="submit" value="Save" />
}
And have a POST action method to handle this
[HttpPost]
public ActionResult Search(CustomerViewModel model)
{
if(ModelState.IsValid)
{
string name= model.Name;
// you may save and redirect here (PRG pattern)
}
return View(model);
}
Assuming your objCustomer.getData() method in your GET Action method returns an object of CustomerViewModel which has a Name property like this
public class CustomerViewModel
{
public string Name { set;get;}
//other properties as needed
}

You can add a parameter to your Search action that accepts an object of Type CustomerModels. That way when you post something back to the controller, the model binder will take the data from the form and generate an object of type CustomerModels which you can then use in your action to work with. For that you need to do two things:
Your view should receive a model of type CustomerModels
Your action should be something like this public ActionResult Search(CustomerModels model)
If you don't want to change your view, that is, you don't want to pass model to your page, you could try and use TryUpdateModel inside your controller, or pass FormCollection object to your Search action and then query that collection.

Related

MVC HTTP Post input return null

Controller:
public ActionResult MyController()
{
ViewBag.DateNow = DateTime.Now.ToString("yyyy-MM-dd");
}
[HTTPPost]
public ActionResult MyController(string fromDate)
{
ViewBag.DateNow = fromDate;
}
View:
#using (Html.BeginForm("MyController", "Account", FormMethod.Post))
{
//datepicker class: bootstrap-datepicker.js
<input id="fromDate" type="text" class="datepicker" />
<buttontype="submit" value="Search" class="btn btn btn-primary">
Search
</button>
}
What I'm trying to achieve is before POST the data that pass into ViewBag.DateNow is the current date and it successfully bring in to the view. However when I'm trying to fill up the input form with (eg: 2016-05-10) and click on the Search button. But seems like the fromDate string return NullReferenceException. I'm trying out with some solution online but I still can't get it right and that's why I decided to get this posted up. Thanks in advance!
For this to work properly you need to specify the name attribute in your textbox. It needs to be the same value as the input variable in your HTTP post action method, namely fromDate. Currently the id attribute is set to fromDate:
<input id="fromDate" name="fromDate" type="text" value="#ViewBag.DateNow" />
If you do not specify this name attribute then when you post your form fromDate will always be null. Specifying it like above will make sure that fromDate will always have a value (if entered).
I want to go a bit off-topic here, I would like to suggest that you make use of view models for your form submissions. Instead of having individual input variables in your action method you can just have your view model as input parameter.
I wrote an answer as to what view models are here, please go and read it if you have the time:
What is ViewModel in MVC?
Working on your example, I would have a view model that contains just one property, namely FromDate. FromDate will contain the value in your textbox. It is setup as a string because you want to pass it a formatted date value:
public class TestModel
{
public string FromDate { get; set; }
}
This value will be set in your HTTP get action method and the view model will be sent to the view:
public ActionResult Index()
{
TestModel model = new TestModel();
model.FromDate = DateTime.Now.ToString("yyyy-MM-dd");
return View(model);
}
In your view you will accept this view model and create the form accordingly:
#model WebApplication_Test.Models.TestModel
#using (Html.BeginForm())
{
#Html.TextBoxFor(m => m.FromDate)
<button type="submit">Search</button>
}
When you submit this form, you need an HTTP post action method to handle the submission. Because the view is bound to the view model, the action method will accept it as an input parameter:
[HttpPost]
public ActionResult Index(TestModel model)
{
// Do what you need to do
string date = model.FromDate;
return View(model);
}
Your way of doing it is also correct. I have just shown you an alternative way to do it. Some day you might have a huge form with many input values, then my approach will be 'cleaner'.
Try this:
1) Replace with [HttpPost] instead of [HTTPPost]
2) You should add name=" " for input like this:
<input id="fromDate" name="fromDate" type="text" class="datepicker" />

string Model, passing value to controller issue

I have a ASP.NET Razor view which binds to string. Its very simple:
#model string
#{
Layout = "~/Views/Shared/_Layout.cshtml";
}
Hello, #Model
#using(Html.BeginForm())
{
<fieldset>
<label for="name" style="color: whitesmoke">Name:</label>
<input type="text" id="name"/>
<br/>
<input type="submit" value="Submit"/>
</fieldset>
}
And a simple controller:
[HttpGet]
public ActionResult Index()
{
object model = "foo";
return View(model);
}
private string name;
[HttpPost]
public ActionResult Index(string name)
{
return View();
}
When I push the submit button, the Index Post action result triggers, but the 'string name' parameter is null. Isn't Razor smart enough to automatically bind this property to my controller from the view because the input id matches the name of the param on the controller? If not, how do I bind this? I know with a model with properties I can use Html.HiddenFor(m => m.Foo), but since there's no properties, I don't know how to call this method properly.. I can set it properly calling Html.Hidden("name","foo"), but I don't know how to pass a the value here. I know I can use jquery call such as:
#Html.Hidden("name", "$('input[id=name]').val())");
This literally sends the jquery string to the controller as the value... I'm not sure what to do at this point. Thanks!
It is smart enough to bind the property, just give your input a name which matches with the action parameter:
<input type="text" id="name" name="name" />

Get value of view element in MVC that not relevant to model

When I have a DropDownList that relevant to Model of view like this:
#Html.DropDownListFor(model => model.Group.Name, selectList)
I Can retrieve Values in controller as follow:
string SelectedGroupName = collection.GetValue("Group.Name").AttemptedValue;
But now I have a DropDownList that not relevant to model but I need the value of that, this is my new DropDown:
#Html.DropDownList("DDName", selectList)
How can I retrieve the selected value of that in controller? is there any hiddenfield or other thing to pass value from view to controller?
Edit
This is my view:
#model PhoneBook.Models.Numbers
#{
ViewBag.Title = "Delete";
}
<h2>
Move And Delete</h2>
<fieldset>
<legend>Label of Numbers</legend>
<div class="display-label">
Delete Label And Move All Numbers with: #Html.DisplayFor(model =>
model.Title)</div>
<div class="display-field">
To #Html.DropDownList("DDName", selectlist)
</div>
</fieldset>
#using (Html.BeginForm()) {
<p>
<input type="submit" value="Move Numbers And Delete Label" name="MDbtn" />
</p>
}
This is my Controller:
[HttpPost]
public ActionResult Delete(int id, FormCollection collection) {
var result = Request["DDName"];
//Use result
return RedirectToAction("Index");
}
but result set to null, why?
I think this must be work:
[HttpPost]
public ActionResult Delete(int id, FormCollection collection)
{
var dd = collection.GetValue("DDName");
.....
}
I think all you have to do is
In your view:
put #using (Html.BeginForm()) { above the <fieldset>, so the #Html.DropDownList("DDName", selectlist) is inside it.
In your controller:
public ActionResult Delete(int id, FormCollection collection, string DDName)
{ [...] }
And I'm fairly sure MVC3 will automagically give you the selected value as parameter to your controller.
If that does not work, try object DDName in your controller instead.
Think the ddl has to be in your form if you want to pass the value in through the form collection
Your problem is, that your dropdown isn't contained inside the form in your view.
You have to put it after BeginForm:
#using (Html.BeginForm()) {
<div class="display-field">
To #Html.DropDownList("DDName", selectlist)
</div>
<p>
<input type="submit" value="Move Numbers And Delete Label" name="MDbtn" />
</p>
}
Then you have can use FormCollection or a designated parameter. The default Modelbinder will work with both approaches:
ActionResult Action (FormCollection collection, string DDName)
You can easily check those issues with fiddler.

FormsCollection in Mvc Controller method - any other way of accessing?

I have a form which I want to post to ensure the page refreshes on posting the data (not the ajax way). The problem is really I only want to post the Id of the record and extract that in the controller method. I'm finding that the form is posting everything (I might not be able to resolve that since the same form is used for updating). But I'd like to be able to have the variable pop into the parameter of controller method rather than extracting from the FormCollection. I've tried the various parameters below, but all are being passed null. Any idea what the problem is?
I have the following in my controller method:
public ActionResult Delete(FormCollection collection)
{
var idToDelete = collection["Current.CommissionStructureId"].ToInt32();
}
// tried the following but none of them bind
public ActionResult Delete(int? Current_CommissionStructureId, int? CommissionStructureId, int? Id, int? id)
{
// none of the above are binding (set to null)
}
You should use HttpPost only for deleting of records
#using (Html.BeginForm()) {
<input type="hidden" name="CommissionStructureId" value="#item.CommissionStructureId" />
<p>
<input type="submit" value="Delete" />
</p>
<p>
#Html.ActionLink("Back to List", "Index")
</p>
}
[HttpPost]
public ActionResult Delete(int CommissionStructureId)
{
CommissionStructure commissionStructure = db.CommissionStructures.Find(CommissionStructureId);
db.CommissionStructures.Remove(commissionStructure);
db.SaveChanges();
return RedirectToAction("Index");
}
When your form value is named Current.CommissionStructureId the default modelbinder will bind it only to a class parameter called Current with a property called Id.
So your options are
Create a small class with one property Id and use it as your parameter type
or
Write a custom modelbinder

Getting posted values in MVC PartialView

I've created a PartialView which I render with Html.RenderPartial, passing the name of the view and the strongly-typed data item to bind to (below):
<% Html.RenderPartial("SearchViewUserControl", ViewData["SearchData"]); %>
The partial view has a form containing a submit button:
<% using (Html.BeginForm("Search", "Home"))
{ %>
...
<div>
<input type="submit" value="Search" />
</div>
<% } %>
I've set a breakpoint in my controller's action method (below) but nothing is set in searchData. What am I doing wrong?
public ActionResult Search(SearchDomain searchData)
{
if (ModelState.IsValid)
{
}
return View();
}
You need to post the actual form elements for anybody to know whats wrong.
The form html is what sets the binding to SearchDomain. You want to have your form elements named like this:
<input name="searchData.SomeProperty">
For them to bind to your action parameter.
In order to pull a SearchDomain object out of your view from a controller method, your view has to either inherit from System.Web.Mvc.ViewPage<Models.SearchDomain>, or a custom ViewModel class that contains a SearchDomain object.
The other way to do it is to have your view inherit from System.Web.Mvc.ViewPage, and use UpdateModel to cast the view data to a SearchDomain object. Something like this:
public ActionResult Save()
{
SearchDomain domain = new SearchDomain ();
UpdateModel(domain , new[] { "Name", "Email", "Phone", ... });
return View(domain);
}
To be honest, I think RenderAction is much easier to use.

Resources