Accessing Data attribute of html input control in MVC2 controller - asp.net-mvc

I am submiiting a form from view which contains input field with specific data attribute
<form>
<input type="text" data-user="001" name="mytext" />
</form>
this from is submitted to a controller
[HttpPost]
public ActionResult Settings(FormCollection formValues)
{
//here i can access input control's value by its name like
string user= formValues["mytext"];
}
but how i can get value of data-user attribute in controller?

I do not think you can do it. You can access session variable from controller like this, however:
string strsetting1 = (string)HttpContext.Session["setting1"];
In your Global.asax.cs:
protected void session_start()
{
Session["setting1"] = "Y";
}

Related

MVC get data from dynamic field

I'm very new in MVC :(
I created a dynamic form by cloning a principal DIV element and its elements. The elements are combobox, textbox and a date textbox. When I create a new "clone", the DIV every member of itself has an incremental ID like tab_Container, tab_Container_1, text, text1, combo, combo1, etc... Now, I'm trying to get the values of each member in the Divs into the controller.
Googling I find something like this:
[HttpPost]
public ActionResult NewEntry(Model Entry)
{
Control myControl = new Control();
myControl.FindControl("Text0");
if (myControl != null)
{
/// apparently, find the control,here i wanna to get the value of each field !! ¿?
/// do i have to create a list[] ... exist something like Entry.Text0 = myControl.value?
}
else
{
Response.Write("Control not found");
}
return View(Entry);
}
Any suggestion? Is Control the best option? Do I have to do something else in Javascript code?
While it's normally better to have some sort of Model / ViewModel this situation is a bit different. MVC binds on the "Name" property of your form inputs.
So say for instance your razor syntax generates something like this:
<form>
<input type="text" name="input1" />
<input type="text" name="input2" />
<!-- etc etc etc -->
<input type="submit" value="submit" />
</form>
since this is dynamically generated and you don't have a model that would cleanly bind to this. You can use the FormCollection type as the parameter of your action. This gives you a collection of all items posted to the server that you could then loop through or peer into to get the properties that you want.
public ActionResult myAction(FormCollection collection)
{
var value = collection["input1"];
var value2 = collection["input2"];
return View();
}

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" />

Preserve action parameter on post

I have two actions to create a Tag, an HttpGet and an HttpPost:
[HttpGet]
public virtual ActionResult New(String culture) {
culture = culture ?? "en-US";
TagNewModel model = new TagNewModel();
ViewBag.Data = new { Culture = culture };
return View(model);
}
[HttpPost, ValidateAntiForgeryToken, ValidateInput(false)]
public virtual ActionResult Create(MarkNewModel model, String culture) {
}
When I submit the form the "culture" in the HttpPost is null ... How can I preserve the culture value I set on the HttpGet?
Thank You,
Miguel
You simply need to include the Culture value into the form with the name that matches the action parameter name. In your case "culture".
In the following example, I am not using any of the Html helpers. I'm just showing one way of doing it.
<form action="create" method="post">
<input type="hidden" value="#(ViewBag.Data.Culture)" name="culture"
</form>

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.

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

Resources