Showing posts with label Razor view. Show all posts
Showing posts with label Razor view. Show all posts

Tuesday, March 25, 2014

FIX: 'Model' conflicts with the declaration 'System.Web.Mvc.WebViewPage.Model'

I suddenly started receiving this error in one of my razor view. The error message was -
'Model' conflicts with the declaration 'System.Web.Mvc.WebViewPage<TModel>.Model'

This error is caused if you use "Model" instead of "model" in one or more lambda expressions (predicates) in your view.

Perform a case-sensitive search for "Model =>", and its very much possible that you may notice this in one or more lambda expressions,
For example,
@Html.EditorFor(Model => Model.BirthDate)
This should be actually, @Html.EditorFor(model => model.BirthDate)
Correcting this should fix the Model conflict error for you in your view.

Thursday, January 2, 2014

Accessing Model property in MVC View from Javascript

For example, you have following model in your MVC application:

public class Employee
{
public string EmployeeName
public int EmployeeNumber
}

You have bound this model to your MVC view (Razor/ Html), and there may be a case when you need to access "EmployeeName" in the Javascript from that view.

You can access value of "EmployeeName" property of your model by following way:

<script type="text/javascript">
function showEmployeeName()
{
alert('@(Model.EmployeeName)');
}

</script>

Thursday, April 19, 2012

Investigation: Values do not retain in model while posting it from view to controller action in MVC

Scenario: My controller action is passing a model to the view, and displaying the fields on my view.
There are few fields which are non-editable (like, ID, etc), and are only for display purpose, so I have placed them directly on view.
There are few fields in that model which are not required to be displayed at all on view, so I have not placed them on view.
The problem is that, when a user clicks Submit to post the view to controller action, the model does not contain their original value for those fields.
How to fix it?

Fix: When you bind a model by passing it from control action to view, you should bind each and every field of the model in view. This will retain their values during HttpPost.

So if there are some fields you want to display them as read-only, or if you do not want to display them at all, then you should still bind them within view. Its necessary if you are posting the view to a controller action (using HttpPost)

The best way is to use hidden tag, using @Html.HiddenFor helper, if you do not want to display the field.
Or use @Html.DisplayFor helper, if you want to display the field in read-only mode.