csefaruk
csefaruk

Reputation: 191

Assign Model property value from JavaScript value

I have a model with the following definition:

namespace ESimSolChemical.Models
{

    public class Employee
    {        
        public int EmployeeID{ get; set; }
        public string EmployeeName{ get; set; }
        public string Age{ get; set; }
        public string Address{ get; set; }

    }

I have Following JavaScript:

<script type="text/javascript">
    $(function () {
        $('#btnEmployeePiker').click(function () {
            var oParameter = new Object();
            oParameter.MultipleReturn = false;
            var oReturnObject = window.showModalDialog('/Employee/EmployeePiker/', oParameter, 'dialogHeight:470px;dialogWidth:550px;dialogLeft:400;dialogTop:100;center:yes;resizable:no;status:no;scroll:no');           
        });
    });
</script>

My Javascript oReturnObject contains two property Like :

oReturnObject.EmployeeID;
oReturnObject.EmployeeName;

Now I would like to assign:

@Model.employeeID=  oReturnObject.EmployeeID;

How can I accomplish this task?

Upvotes: 6

Views: 40448

Answers (4)

Abhishek Khandare
Abhishek Khandare

Reputation: 19

It seems like you are going to assign values of the model(server-side) through JavaScript (Client-side). This is not the correct way to update the server-side Model object from client-side code. Client-side JavaScript runs on the user's browser, while the server-side Model object is stored on the server. Therefore, you need to use some kind of communication between the client and server to update the server-side Model object. like AJAX.

you can refer : https://www.geeksforgeeks.org/how-to-make-ajax-call-from-javascript/ for ajax

Upvotes: 0

Dev Kumar
Dev Kumar

Reputation: 117

This is what I have used:

@{
   @Convert.ToString("var refID = " + @Model.RefID + ";alert(refID);")
}

and its working fine.

Upvotes: -1

Brendan Vogt
Brendan Vogt

Reputation: 26058

You cannot set server side values with Javascript. You could bind these values to input fields like textboxes or hidden fields and then use Javascript to modify these values of these input fields.

Take a look at these articles, it might help you out:

Upvotes: 9

twoflower
twoflower

Reputation: 6830

You can't execute a server-side code like that in JavaScript.

You need to somehow post the updated values back to the server to process them.

Take a look at KnockoutJS, it makes things like this very easy. Basically, you will just serialize your model class on the client side to a JavaScript object, work with it until you decide to save it back and then you send it to the server as JSON, which will allow you to have an action method like this

public ActionResult UpdateEmployee(Employee employee)
{
    // Update the database...
    //
}

The page linked above has plenty of tutorials to start with.

Upvotes: 0

Related Questions