Get value of view element in MVC that not relevant to model - asp.net-mvc

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.

Related

Pass argument to controller on submit

So, i started learning MVC, and i need to pass an email to a controller. (Trying to make a standard email signup)
Therefore i have an input and a button which (should) pass the input to an argument accepting controller and then redirect to another view.
I have the following controllers:
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult Index(string mail)
{
person = new EmailSignup{Email = mail};
return RedirectToAction("details");
}
public ActionResult details()
{
return View(person);
}
This is what i have in my View:
#using (Html.BeginForm("Index", "Home", FormMethod.Post))
{
<form class="col-md-12">
<div class="form-group form-inline">
<label class="margin20">Sign up for newsletter</label>
<input type="Email" class="form-control" style="display:inline-block; max-width:200px" id="mail" placeholder="Example#Example.com" />
<button type="submit" class="btn btn-default" style="display:inline-block" id="emailSignup">Signup</button>
</div>
</form>
}
It redirects to my "details" view, but my email is not showing.
Furthermore, is this best practice? would i want to do it like this?
#using (Html.BeginForm("Index", "Home", FormMethod.Post)) renders a form, you don't need a second one inside it (if you need to add the class, you can use an overload of Html.BeginForm). Your input contains an id property, but not a name property. name is what's used when an action happens inside a form.

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 can i invoke a method in a different controller including parameters using mvc 6

I'm new to developing web applications and most importantly new to mvc. I'm trying to navigate from one view to another controller action including parameters. I have the below code in my currently displaying view:
<p>
<a asp-controller="Working_set" asp-action="Create">Create new Working set</a>
</p>
#foreach (var item in Model)
{
<div class="col-sm-6 col-md-3">
<div class="thumbnail tile tile-medium">
<a asp-controller="SelectedWorking_set" asp-action="index">
<h2>
#Html.DisplayFor(modelItem => item.Name)
<input name="workingSetID" type="hidden" value="#item.Working_setID" />
</h2>
</a>
</div>
</div>
}
How can i use the Working_setID in the controller SelectedWorking_set below:
[Route("SelectedWorking_set")]
public class SelectedWorking_setController: Controller
{
private FlightmapContext _context;
public SelectedWorking_setController(FlightmapContext context)
{
_context = context;
}
public IActionResult Index()
{
return View();
}
[HttpPost("Index")]
public IActionResult Index([FromBody]int workingSetID)
{
//return View(_context.Project.ToList());
return View();
}
}
You need to pass input name to your controller method like below example;
<input name="workingSetID" type="hidden" value="#item.Working_setID" />
here "workingSetID" name we need to pass your controller method, Suppose your method name is "Index" then you need to write like this in your controller.
[HttpPost]
public ActionResult Index(string workingSetID)
{
//Code here
}
like this you will get "Working_setID" value in your controller method. And also you need submit button to post this value to controller.

Razor checkboxfor not working as expected

There are razor checkbox controls in application which needs to be repeated for each of the collection. But for the collection number second onwards below code passes nothing as value for checkbox:
<div class="checkbox">
<label class="checkbox-inline">
#Html.CheckBoxFor(m => m.Collection[i].Item)Some Label
</label>
</div>
The viewmodel is:
public class Items{
public List<Collection> Collection{get; set;}
}
public class Collection{
public bool Item { get; set; }
}
Assuming your HttpPost action's parameter is an object of
[HttpPost]
public ActionResult Create(Items model)
{
//to do : Save and Redirect
}
You need to make sure that the checkboxes in your form will have the name matching to your ViewModel property hierarchy. So , for model binding to work, you need to have your checkboxes with names like this
<input name="Collection[1].Item" type="checkbox" >
So in your view, Make sure you manipulate the name like that
#model Items
#using (Html.BeginForm())
{
for (int index = 0; index < Model.Collection.Count; index++)
{
var collection = Model.Collection[index];
#Html.CheckBox("Collection["+index+"].Item",collection.Item)
}
<input type="submit"/>
}
Another (better) option is to use Editor Templates. With this approach, you do not need to manipulate the form field name. Here is a complete post which explains the step by step
Instead of Item write selected
<div class="checkbox">
<label class="checkbox-inline">
#Html.CheckBoxFor(m => m.Collection[i].selected)Some Label
</label>
</div>
Or try this
#Html.CheckBoxFor(m => m[i].Checked,new {Style ="vertical-align})

passing value from view to controller in 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.

Resources