.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
Sign In
Win Surprise Gifts!!!

Top 5 Contributors of the Month
Gaurav Pal
Post New Web Links

view the modelstate errors in action method

Posted By:      Posted Date: October 18, 2010    Points: 0   Category :ASP.Net

for debugging purposes, how do I see the ModelState errors from code in the action method?  ModelState.IsValid returns false. I want to copy the error messages to a variable so I can display them in the debugger.



View Complete Post

More Related Resource Links

Action method returning an ActionResult used in a Action method


Hell all,

I have the Index action method calling a method that itself is an action method.

Example :

public ActionResult Index()
   //do stuff
   ActionResult result = MethodB();
   // ?? what to return here ??

public ActionResult MethodB()
   //do stuff

  return View("Index);

What to do in this case ?

Calendar and grouped view causes errors

Hello, I've come across a bizarre situation on a standard web part page. First I add a simple (or so I thought) document library web part with a view grouped on a column. The view is collapsed. Then, I add a calendar view to a page. Immediately, my grouped doc lib view turns into a site navigation web part with no resemblance to the doc lib. If I change the doc lib view to a non-grouped view, all is well again. I've built three different pages on different sites and can re-create this problem every time. If I change the Calendar web part to a detail rather than a calendar view, the page goes back to normal. Any idea what is going on here or how I can mix a calendar and a grouped view on the same page?   Thanks.

(MVVM): Call Method On ViewModel From View

Hey All,   In my View, I would like to call a method on my ViewModel (all from XAML). View: <!--Parameters--> <ListView Grid.Row="2" DataContext="{Binding}" ItemsSource="{Binding}"> <ListView.View> <GridView AllowsColumnReorder="True"> <GridViewColumn Header="Name" DisplayMemberBinding="{Binding Key}"/> <GridViewColumn Header="Value"> <GridViewColumn.CellTemplate> <DataTemplate> <TextBox Text="{Binding Value, Mode=OneWay}" MinWidth="100" /> </DataTemplate> </GridViewColumn.CellTemplate> </GridViewColumn> </GridView> </ListView.View> </ListView> ViewModel (the Method I want to call): public ReadOnlyScriptParameterCollection GetParameters(string scriptFullTypeName) { ReadOnlyScriptParameterCollection sps = null; var scriptHost = ScriptHost.Create<JdsScriptHost>(); scriptHost.LoadFromAssembly(ScriptAssemblyPath, scriptFullTypeName); sps = scriptHost.ScriptParameters; return sps; } Is there

PartialViews and View ModelState



I am using MVC2.

I have a 'Person View' that is bound to a 'Person model' that contains a 'Car Partial View' which is bound to a 'Car model'. The Person and the Car model are not related in any way nor do I want to create a new ViewModel for the Person View that contains the Person and Car model (I want the page to be dynamic and at runtime I decide if I need the Car Partial View. I may also in the future want to add more partial views to the Person View such as Hobbies, Social Networks, etc... so I don't want to keep extending the Person ViewModel)

The Car Partial View sits inside the Person's View BeginForm() and what I want to do is on submit of the Person View validate the Person Model and the Car Model and then return any errors via the ModelState.

The problem I have is that the ModelState only knows about the Person model and not the Car model.

Can anyone suggest how I can ensure on Submit that the ModelState of the Person and Car are validated? Do I need to add a HttpPost ActionResult to the Car View's controller to do the validation, if so when would this be executed? Which ModelState do I update, the Person or the Car?

If you need anymore clarification please ask...

Thanks in advance

Sending JSON Array to an ASP.NET MVC Action Method Argument


 <input type = "submit" onclick = "savePayment()"  value = "Test"/>

    <script type="text/javascript">
        function savePayment() {
            //Creating some test data
            var lineItems = new Object();
            lineItems.Entrys = new Array();
            lineItems.Entrys[0] = new Object({ Name: "Dung", Age: "21"});
            lineItems.Entrys[1] = new Object({ Name: "An", Age: "25" });

            //Posting them to server with ajax
                type: 'POST',
                contentType: 'application/json; charset=utf-8',
                url: '<%=Url.Action("TestArray", "Json") %>',
                dataType: 'json',
                data: $.toJSON(lineItems),
                success: function (result) {
                    if (result) {
                    else {

passing values to object properties of action method parameter


I have an action method that accepts a single parm.

That parm is an object with multiple properties. MVC correctly maps values from the querystring
to properties in the parm object by matching property name to querystring value name. 
Problem is, properties in the action method parm object which are themselves objects with
properties, are not assigned their matching values from the querystring. The class object has a
constructor which accepts a single string parameter.

How do I assign to properties of an action method parameter which are themselves class objects?



                <%: Html.ActionLink("Edit", "ProductMasterEdit", 
                       new { ProdKey=item.ProductKey.Value, 
                       ProductKey = item.ProductKey.Value })%> 

    public ViewResult ProductMasterEdit(ProductMaster Item)

  public partial class ProductMaster

    public ProductKey ProductKey
      get { return new ProductKey(this.ProdKey); }
      set { this.ProdKey = value.Value; }


jQuery post to an action method



I hope this is the right section to post this, as it does seem to be an MVC related issue. I'm trying to use the jQuery.post() function to post an object to an action method, but for some reason the nested objects aren't initialised properly when they're received by the action method.

Here's my javascript code:

var data = {
    Id: 10,
    User: {
        Id: 5
$.post("/Home/SaveCompany", data, function (data) {

And my action method:

public ActionResult SaveCompany(Company company)
    if (company.Id > 0) {
    } else {
    return Json(new { id = company.Id });

company.Id has a value of 10, but company.User.Id is 0. Any ideas what I'm doing wrong? I've not named any properties incorrectly, by the way.


Deleting a Controller Action and its View in one step


Since a Controller Action and its View are associated with each other I would think that there would be a way to delete both in one step.

Is that possible? 

Upload with strongly-typed view - Create Method



How to can upload a file to database with strongly typed view - create method?

Picture is a binary db column

<%: Html.TextBoxFor(Function(model) model.Resim)%>


 How i can translate "TextBoxFor" to "UploadFileFor"?

Cascading action for multiple partial view in one view



I would like to create one view for my CRUD actions.  The view contains 3 basic DIV updatetargets ("search form", "search result listing" and "action" (would be create,detail,edit,delete).  Basic flow would be: "Search" updates the "Search Result Listing", click on CRUD actions in listing would show partial view in "action". 

Problem how do I call to refresh the "Listing" after I do any add/update/delete without having user click search again?


<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage" %>

<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">

<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">

    <h2>Student Example</h2>
        <% using (Ajax.BeginForm("Search", "Student",
               new AjaxOptions { UpdateTargetId = "divSearchResult" }))
        { %>
        <%= Html.ValidationSummary(true) %>
            <legend>Student Search Criteria&

Problem in passing Json collection object from View to Action



I am trying to send json data from view to controller action.  But the issue is the data is not populating in the action parameter List<Score>.

View Model:
public class Score
   public int QuestionId { get; set; }
   public int PrevAnswerId { get; set; }
   public int CurrAnswerId { get; set; }
   public string CurrAnswerName { get; set; }

Json Data look like:
{QuestionId:1, PrevAnswerId:3,  CurrAnswerId:3,  CurrAnswerName:'Known to Broker'},
{QuestionId:2, PrevAnswerId:7,  CurrAnswerId:7,  CurrAnswerName:'Completed'},
{QuestionId:3, PrevAnswerId:10, CurrAnswerId:10, CurrAnswerName:'Report'}

On window load,  I will construct the Json object using "eval()" function and do some operation in the data before its save.

On Save Click, I will call the action through the ajax call.
        url: url,
        type: "GET",
        dataType: 'json',
        data: {score: ScoreJson},

Action method taking model object



I've an action method like the below:


public void Edit(Movie movie)



Movie has fields Id, Name. View is displaying name only in textbox. When button is clicked, the above action method's movie is populates with the updated name value but Id is 0, actually that record's id is 4. Thatswhy my updating of record is not working. Why MVC is putting 0 into id?


passing data from a DropDownListFor to Action method in MVC3 (Razor)


I have two questions regarding passing the selection of a dropdownlist to an action method in an MVC controller:


1. What are the options for actually passing the selection back to the action method as a parameter?  The only thing I've been able to get to work is to name the parameter and the select list the same.  For example, my action method looks like:

        public ActionResult Example(int? FeatureId)

// do something with FeatureId
            return View(someobject);

and the static HTML list looks like:


<select name="featureId1">

2.  How can I use an extension method to name the select list appropriately?  I've been trying to do it with the htmlAttributes method but I find that this only works on the id, not the name.  E.g.:



@Html.DropDownListFor(x => x.objects, new SelectList(Model.objects, "FeatureId", "FeatureName"), new { @id = "FeatureId", @name = "FeatureId" })







Thinking about new C# method prototypes: object as dictionary

I recently had to write a small Flickr API. I know many .Net API for Flickr already exist but I needed one for a Silverlight application. Whatever, it's only about building some querystrings so I did it by myself. It's been an opportunity to think again about a classical question: how to pass parameters to a method ?

Imagine you have a generic method to call some Flickr functions.

Truly Understanding View State

This article provides a detailed understanding of the ViewState.

GridView Parent Child View with JQuery Effects

I was just checked how to add some more cool effects to the GridView control using JQuery. In this post I will display parent-child data in the GridView control with some help of the wonderful JQuery library.

Let's first populate the GridView control.

Model View Controller (MVC) for ASP.NET

Model View Controller (MVC) architectures, immediately wonder how the MVC pattern can be applied in an ASP.NET world. This article will demonstrate how the MVC pattern can be applied to an ASP.NET web application and still maintain the basic Microsoft supplied architecture.
ASP.NetWindows Application  .NET Framework  C#  VB.Net  ADO.Net  
Sql Server  SharePoint  Silverlight  Others  All   

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend