ASP.NET MVC and Model Binding? - asp.net

In my effort to convert few asp.net webforms into MVC razor views, I have converted all server side controls into equivalent HTML tags.
I am a bit late to realise that I should have used MVC HTML helpers, The issue here is I am not able to bind HTML tags values to strongly typed view request.
Is there any way in MVC-3 to map Model properties with HTML tags, without using HTML helpers?
Consider following Model class:
class Person
{
public string FirstName{get; set;}
}
View
#model MyApplication.Models.Person
<input type="text" id="txtFirstName" **???**/>
In place of ??? I am expecting some attribute here to bind input to FirstName property of Model.
Is it feasible ?

The DefaultModelBinder is using the name attribute to bind values from the HTTP request to your model. If this convention doesn't suit your needs, you can write your own ModelBinder.
So in your case the following code should work (but I would recommend using HTML helpers anyway, because with HTML helper you can use automatic unobtrusive validation)
Controller:
public ActionResult Create(Person person) {
...
}
View:
#model MyApplication.Models.Person
<input type="text" id="txtFirstName" name="FirstName" />

Related

How to post a form to an url in asp .net mvc3?

Im new to asp .net mvc3. I have a requirement that i post a form to a url say "www.abc.com/asa" . I have added a submit button to my application. But every time i click the button, form gets submitted to corresponding controller. How can i post to my required url?
Normally in mvc we follow below convention:
[httpGet] //default not to mention
public ActionResult Index()
{
// Todo code here
}
[httpPost]
public ActionResult Index(FormCollection collection)
{
// Form submit here, all form data available here
}
But in your case you may write following in your view:
#using (Html.BeginForm("ActionName", "Controller", "FormMethod", "HTML Attributes"))
{
// Here Controller: it defines whose actionmethod need to be called when form get submitted.
}
EX:
#using(Html.BeginForm(null, null, FormMethod.Post, new {#action="http://www.abc.com/asa"})
{
}
In this case I would suggest using a standard html <form /> tag with the appropriate url in action parameter.
BeginForm helpers always take action and controller as parameters - you can't use the standard ones.
If you want you can define your own helper too. I would do that if this is a bigger application and you'll be using this multiple times.
<form action="www.abc.com/asa" method="POST">
<legend>
Foo
</legend>
<fieldset>
<p>Fields</p>
</fieldset>
<input type="submit" name"submitForm" value="submitForm" />
</form>

How to read content between tags of asp.net server control

I'm writing an asp.net server side control which has a few short parameters passed into it, but also the need to allow a large piece of custom HTML code to be supplied.
The easiest way of doing so I thought was to allow to be specified between the tags of the server control, like so:
<MyControl:Example Runat="server" Id="myControl" Message="This is a message">
<p>This is a long piece of HTML a few dozen lines long...</p>
</MyControl>
How can I access the text between the tags from inside my custom server control?
You need to create a templated control:
<MyControl:Example Runat="server" Id="myControl" Message="This is a message">
<HtmlContent><p>This is a long piece of HTML a few dozen lines long...</p></HtmlContent>
</MyControl>
Where HtmlContent is your template. Generally when I need templates, I simply use PlaceHolder instead.
public class MyControl : CompositeControl
{
[TemplateContainer(typeof(PlaceHolder))]
[PersistenceMode(PersistenceMode.InnerProperty)]
public PlaceHolder HtmlContent { get; set; }
... render stuff
}
Here's an example on MSDN:

Passing Data from Usercontrol to controller

I am new to MVC, and trying something and got stuck somewhere in between.
I have a user control there I have three textbox html type(ID, Lastname, firstname) and a submit buttom.
I set the button like
<input type="button" value="Search"
onclick="location.href='<%= Url.Action("action", "controller") %>'" />
I have called this usercontrol on some view through
<%= Html.Partial("ucName") %>
Now on pressing that button(on user control) I need to pass the data from these textboxes to controller again to some specific action(Http Post action). By using this data I want to do some database interaction and storing the result in a dataset and pass this data set to same view again to show up in some Grid.
I know the first part in conventional Asp.net can be done by raising the event through delegate but don't know how to do that in MVC.
In your actionresult you should have;
public ActionResult(MyModel model)
{
//now do something with model
}
Get rid of the button and use a submit button instead and then use BeginForm so that it will submit to the same action and controller.
MyModel should contain the three fields and your model should inherit from MyModel as well so that MVC knows where to get the data from.
Have you gone through the NerdDinner sample yet because it sounds like you haven't. you need to do that first to get an appreciation of how MVC models and view work.
Can't you simply use a submit button that will post data to the desired controller action:
<% using (Html.BeginForm("action", "controller", FormMethod.Post)) { %>
<!-- ... your textboxes here ... -->
<input type="submit" value="Search" />
<% } %>
You could also use FormMethod.Get if you want the parameters to be passed in the url.

ASP.NET MVC. No idea how to use Url.action to pass an object to the controller

I am new to asp.net MVC. I was able to create my view and display the data (Gridview). Additionally, I was able to create a hyperlink (using Url.Action) passing string and int types. However, I want to create a hyperlink that it is referencing a more complex type. The class associated with my view has a reference to a List. What I want is to create an additional ActionResult in my controller that gets as a parameter List (See below)
public ActionResult ViewItems(List<Items> c)
{
return View(c);
}
My idea is when is to be able to pass that List to the controller and then the controller will call the corresponding view. I tried (See below) but I just get blank.
<asp:HyperLink ID="LinkContractID" runat="server" NavigateUrl='<%#Url.Action("ViewItems", new {c = **((Contract)Container.DataItem).ContractItems.ToList<Items>(**)}) %>'
Text='<%# Eval("ContractId") %>'></asp:HyperLink>
Like in the previous answer, you don't use asp controls. There are pros and cons with Html.ActionLink however, it isn't so good if you want to put a link around an image for instance. In this case the syntax would be
<a href="<%= Url.Action(
"ShowListPage", "MyController", new { modelId = 101 }) %>">
<img src="img.gif" />
</a>
Also with your action in the controller, you would ideally be looking to have this go and get the model to pass to a view strongly typed to this model. So you have a model object with a constructor taking an id, for instance
public MyModel(int modelId)
{
this.TheListThatHoldsTheGridData = MyDataLayerProc(modelId);
}
This way you can have your action in the MyController controller, return the view ShowListPage (associated with a MyModel instance) like so
public ActionResult ShowListPage(int modelId)
{
return View(new MyModel(modelId));
}
Hope this helps,
Mark
If you are looking for a grid, this tutorial shows how to create a grid with MVC.
With MVC, you shouldn't use Gridview and asp: controls. If you want to generate a link, just use <%=Html.ActionLink(...) %> with the necessary parameters.

Implementing a search page using url parameters in ASP.NET and ASP.NET MVC

Let's say I have a search page called Search.aspx that takes a search string as a url parameter ala Google (e.g. Search.aspx?q=This+is+my+search+string).
Currently, I have an asp:TextBox and an asp:Button on my page. I'm handling the button's OnClick event and redirecting in the codebehind file to Search.aspx?q=
What about with ASP.NET MVC when you don't have a codebehind to redirect with? Would you create a GET form element instead that would post to Search.aspx? Or would you handle the redirect in some other manner (e.g. jQuery event attached to the button)?
You need to understand that MVC doesn't directly reference .aspx pages like WebForms in its URLs. Its main purpose is to separate concerns, that is model (data), controller (logic), and view (presentation).
First, you'd have to create a route matching your URLs, which would now look like this for example : /home/search/This+is+my+search+string
This would call the Search action method of the Home controller, which would get "This is my search string" as an input parameter. This action is responsible for accessing the model and pulling the results probably from a database.
Typically, your search action would then return a ViewResult containing the view placed in the folder /Views/Home/Search.aspx. Here, you can use neither the Postback functionality nor the events of your Web controls like in WebForms, because MVC applications are stateless and not event-driven. It's more like a request/dispatch way of doing things.
Read more about MVC here.
Create a user control called Search.ascx with a form:
<% using (Html.BeginForm ("Search", "Home")) { %>
<input name="search" type="text" size="16" id="search" />
<input type="image" name="search-image" id="search-image" src="search.gif" />
<% } %>
And in your search action all you need is the following:
public class HomeController : Controller
{
public ActionResult Search (string search)
{
throw new Exception (string.Format ("Search: {0}", search));
}
}
In your master page or wherever you can then add
<% Html.RenderPartial ("Search"); %>
You can use a simple javascript in the button's onclick to redirect to the search page:
Search <input type="text" id="go" size="4" /><input type="button" value="<%=Html.Encode(">>") %>" onclick="javascript:window.location='<%=Url.Action("Search", "Home") %>/' + document.getElementById('go').getAttribute('value')" />

Resources