Model Binding using ASP.NET MVC, getting datainput to the controller - asp.net-mvc

Pretty Basic one here guys.
I have a View which holds 2 textfields for input and a submit button
<%using (Html.BeginForm("DateRetrival", "Home", FormMethod.Post)){ %>
<%=Html.TextBox("sday")%>
<%=Html.TextBox("eday")%>
<input type="submit" value="ok" id="run"/>
<% }%>
the following controller action which I want to bind the data input is as follows
[AcceptVerbs(HttpVerbs.Get)]
public ActionResult DateRetrival()
{
return View();
}
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult DateRetrival(string submit)
{
return null;
}
When I debug this and look in the action methods parameter, the value is null. When I've entered values in both textboxes and and clicked the submit method.

You probably want to do something like this:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult DateRetrival(string sday, string eday)
{
return null;
}
Ideally, though you probably want to be passing a model to your controllers:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult DateRetrival(DateModel dates)
{
var date1 = dates.sday;
var date2 = dates.eday;
return null;
}
See http://msdn.microsoft.com/en-us/library/dd394711.aspx

Add parameters to catch each input field value.
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult DateRetrival(string sday, string eday)
{
return null;
}

Try:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult DateRetrival(string sday, string eday, string submit)
{
return null;
}
and if you want sumbit button value
<input type="submit" value="ok" id="run" name="submit"/>
If you want to have value posted, name attribute has to be set. Html.TextBox automatically sets name from parameter.

Related

Returning data from the View to the Controller

After the user has edited data in my View, how to I get the data back to my Controller so I can update my database?
Controller
public ActionResult Cv(int Id)
{
Cv CvBlog = new Cv();
CvPerson = db.Cv.Find(Id);
return View(CvBlog);
}
View Example
In this case I'd like to return the new value for Name
<input type="text" class="form-control" value="#Model.Name" id="name" placeholder="Name">
Thank you very much
One option is to add the id's of the HTML inputs to the paramter list of the return function like so:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Cv(int id, string name)
{
//TODO: update Cv by whatever means you determine
return View("Index");
}
A better option would be to create a ViewModel that would capture the values (still based on the id's of the HTML inputs). This way you can also do some simple field/property level checking on them.
View Model:
public class CvEditViewModel
{
public int Id { get; set; }
[Required]
[MaxLength(50)]
public string Name { get; set; }
}
Controller:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Cv(CvEditViewModel model)
{
if (ModelState.IsValid == true)
{
//TODO: update Cv by whatever means you determine
return View("Index");
}
return View(model);
}
instead of value attribute use the name attribute in view as follows.
<input type="text" class="form-control" id="name" name="#Model.Name">
to get the value in controller use string name=Request["Name"] Request["Name"] will have the value which the user has entered
in view just set name property
<input type="text" class="form-control" value="#Model.Name" name="name" id="name" placeholder="Name">
in controller
[HttpPost]
public ActionResult Cv(int id, string name)
{
//TODO: update Cv by whatever means you determine
return View("Index");
}

ASP.NET MVC 5: passing POST data between views

I'd like to ask a very simple question from a rookie. I want to pass data from view Alpha.cshtml, into controller HomeController.cs with action Beta(), and then display this data in view Beta.cshtml.
Here's my Alpha.cshtml:
#using (Html.BeginForm("Beta", "Home", null, FormMethod.Post, null))
{
#Html.TextBox("data")
<input type="submit" value="Submit" />
}
Here's my Beta.cshtml:
<p>The submitted value is: #ViewBag.Data</p>
And here's my Beta() action:
public ActionResult Beta()
{
ViewBag.Data = ???
return View();
}
What do I put in place of the ???
Thanks!
When the form is submitted, all form input fields will be posted to the server. ModelBinding will take care of reading the posted values and supplying them to your action method in the list of parameters.
[HttpPost]
public ActionResult Beta(string data)
{
ViewBag.Data = data
return View();
}

getting values View data in controller

i did this all but now how to get values being typed in Textbox, password box etc in CONTROLLER. I defined all necessary methods, boxes and buttons etc. So the only problem is to get values in controller and then to send them to model for accessing db data
.csHtml
#using (Html.BeginForm("register","Home", FormMethod.Post, new {id="submitForm"}))
{
<div>
<i>#Html.Label("Name:")</i>
#Html.TextBox("txtboxName")
</div>
<div>
<i>#Html.Label("Email:")</i>
#Html.TextBox("txtboxEmail")
</div>
<div>
<i>#Html.Label("Password:")</i>
#Html.Password("txtboxPassword")
</div>
<div>
<button type="submit" id="btnSubmit" name="Command" value="Submit">Submit</button>
</div>
}
Controller code:
namespace LoginSys.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
ViewBag.Message = "Registration";
return View();
}
[HttpPost]
public ActionResult register(string command, FormCollection formData )
{
if (command == "submit")
{
var name = formData["txtboxName"];
var email = formData["txtboxEmail"];
}
return View();
}
}
}
i'm intentionally using this way of coding it instead of complex and advance one. Just help me to get values in controller
[HttpPost]
public ActionResult register(YOURMODEL model)
{
//db operation
return View();
}
NOTE: make sure your textbox name should be same as your model name
You should use viewmodels. create a model for the view that can be posted to the action. However, if you wish to continue your current approach you need to change the controller action to something like this:
[HttpPost]
public ActionResult register(string btnSubmit, string txtboxName, string txtboxEmail, string txtboxPassword)
{
if (command == "submit")
{
}
return View();
}
if this doesn't work, you can test it by using this:
[HttpPost]
public ActionResult register(FormCollection form)
{
if (command == "submit")
{
}
return View();
}
When you debug you can check the 'form' parameter and see that your fields exists in the form, and get the proper names for the parameters you need.

How do I populate HTML content with new values once data has been changed on postback?

I have MVC3 razor application. Once I'm submitting a form and in Action i'm changing ViewModel content, i can't see new values populated.
There was a topic about that in MVC2 where guys told that it may be fixed in MVC3
http://aspnet.codeplex.com/workitem/5089?ProjectName=aspnet
Can you tell if there is an option to do that or what is the better way(workaround) to update UI without JavaScript using postbacks?
Action:
[HttpPost]
public ActionResult Index(MyViewModel model)
{
model.Value = "new value"
return View("Index", model);
}
UI:
#Html.HiddenFor(x => x.Value)
ViewModel:
public class MyViewModel
{
public string Value { get;set; }
}
Looks like it's using the ModelState values that were posted.
If you clear the ModelState using ModelState.Clear() the new value you set should be in the hidden field.
You should use form and to post it to action.
#model MyViewModel
#using (Html.BeginForm("Index", "Home", FormMethod.Post))
{
#Html.HiddenFor(x=>x.Value)
<input type="submit" value="Submit" />
}
Controller
//
public ActionResult Index()
{
MyViewModel model = new MyViewModel();
model.Value = "old value";
return View("Index", model);
}
[HttpPost]
public ActionResult Index(MyViewModel model)
{
//get posted model values (changed value by view "new value")
string changed_value = model.Value;
// you can return model again if your model.State is false or after update
return View("Index", model);
}

Model change in post action not visible in Html.TextBoxFor?

This must be something very obvious but for me it looks very strange. I have simple controller, model with one property, and view which displays value of property and renders editor for that property. When I click the button, form is posted and exclamation mark is appened to property. This exclamation mark is visible in my view but only in p tag, not in input tag rendered by Html.TextBoxFor().
Why Html.TextBoxFor() ignores that I updated my model in post action?
Is there any way to change this behavior of Html.TextBoxFor()?
View
#model ModelChangeInPostActionNotVisible.Models.IndexModel
#using (Html.BeginForm())
{
<p>#Model.MyProperty</p>
#Html.TextBoxFor(m => m.MyProperty)
<input type="submit" />
}
Model
namespace ModelChangeInPostActionNotVisible.Models
{
public class IndexModel
{
public string MyProperty { get; set; }
}
}
Controller
namespace ModelChangeInPostActionNotVisible.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
return View(new IndexModel { MyProperty = "hi" });
}
[HttpPost]
public ActionResult Index(IndexModel model)
{
model.MyProperty += "!";
return View(model);
}
}
}
HTML after clicking on submit button
<form action="/" method="post"> <p>hi!</p>
<input id="MyProperty" name="MyProperty" type="text" value="hi" /> <input type="submit" />
</form>
This is by design.
The helper methods are using the ModelState, thus if the response of your request is using the same Model, it will display the value that was posted.
This is to allow you to render the same view in the situation where the validation would have failed.
To make sure you display the new information add : ModelState.Clear(); before you return.
Read more here : http://blogs.msdn.com/b/simonince/archive/2010/05/05/asp-net-mvc-s-html-helpers-render-the-wrong-value.aspx
namespace ModelChangeInPostActionNotVisible.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
return View(new IndexModel { MyProperty = "hi" });
}
[HttpPost]
public ActionResult Index(IndexModel model)
{
model.MyProperty += "!";
ModelState.Clear();
return View(model);
}
}
}
Yan Brunet is absolutely correct that the variable needs to be removed from the ModelState in order to be modified in the controller. You don't have to clear the entire ModelState, though. You could do the following to remove just the variable to want to modify:
ModelState.Remove("MyProperty");
This would be useful in case you wanted to retain other values which the user had entered.

Resources